import json
import os
import re
import uuid
from datetime import datetime

import xlrd
from dateutil.relativedelta import relativedelta

from Administrative_office_system.settings import post_url
import requests, base64, urllib.parse
import xlwt
from django.core.paginator import Paginator, PageNotAnInteger
from announcements import public_file
from administrative.public_file import ParseWord, PDFConverter
from django.db.models import Q
from django.shortcuts import render, redirect
from django.views import View
import xlrd2
from django.shortcuts import HttpResponse

from NewFlowLogic.models import *
from logistics.MessagePushOperationRecords import RecordAndPush
from Oa_system.models import Staffing
from administrative.models import Company, Topicsattachments, ConferenceMemo, Topics, PaymentApproval, \
    PaymentApprovalRecord, ContractApproval
from finance.models import *
from personal_center.models import User, SealApply, SealApplyAuditRecord, seal, MakeCopy


class ImportSalaryRecordView(View):
    def post(self, request):
        files = request.FILES.get('file')
        year = request.POST.get("year", '')
        month = request.POST.get("month", '')
        FileType = request.POST.get("FileType", '')
        items = []
        if FileType == '1':
            wb = xlrd.open_workbook(filename=None, file_contents=files.read())
            sheet = wb.sheet_by_index(0)  # 通过索引的方式获取到某一个sheet，现在是获取的第一个sheet页，也可以通过sheet的名称进行获取，sheet_by_name('sheet名称')
            rows = sheet.nrows  # 获取sheet页的行数，一共有几行
            if rows < 2:
                returnDict = {'code': 500, 'message': '不能为空数据'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            try:
                for i in range(1, rows):
                    wages_data = sheet.row_values(i)
                    job_number = str(int(wages_data[0]))

                    user = User.objects.get(job_number=job_number)
                    record_obj = SalaryRecord(user=user, personnel_number=job_number, real_name=wages_data[1], personnel_category=wages_data[2], company=wages_data[3], bank_account=wages_data[4],
                                              post_wage=wages_data[5], salary_level_salary=wages_data[6], standard_performance=wages_data[7], protective_tape=wages_data[8], car_tape=wages_data[9],
                                              health_allowance = wages_data[10], labor_insurance=wages_data[11], total_payable=wages_data[12], endowment_insurance=wages_data[13], occupational_annuity=wages_data[14],
                                              medical_insurance=wages_data[15], unemployment_insurance=wages_data[16], housing_fund=wages_data[17], deduction_insurance=wages_data[18], deduction=wages_data[19],
                                              hydropower=wages_data[20], other=wages_data[21], membership_fees=wages_data[22], total_deduction=wages_data[23], predict_amount=wages_data[24], month=month, years=year, types=FileType)
                    items.append(record_obj)
            except Exception as e:
                returnDict = {'code': 400, 'message': str(e)}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            SalaryRecord.objects.bulk_create(items)
        else:
            wb = xlrd.open_workbook(filename=None, file_contents=files.read())
            sheet = wb.sheet_by_index(0)  # 通过索引的方式获取到某一个sheet，现在是获取的第一个sheet页，也可以通过sheet的名称进行获取，sheet_by_name('sheet名称')
            rows = sheet.nrows  # 获取sheet页的行数，一共有几行
            items = []
            print("rows: ", rows)
            if rows < 4:
                returnDict = {'code': 500, 'message': '不能为空数据'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            try:
                for i in range(3, rows):
                    wages_data = sheet.row_values(i)
                    print(wages_data[4])
                    job_number = str(int(wages_data[4]))

                    user = User.objects.get(job_number=job_number)
                    Perfor_obj = PerformanceRecord(user=user, department_number=wages_data[0], department=wages_data[1],
                                              post=wages_data[2], category=wages_data[3], job_id=wages_data[4], names=wages_data[5], bank_number=wages_data[6],
                                              workload_performance=wages_data[7], management_performance=wages_data[8], night_performance=wages_data[9],
                                              consultation_performance=wages_data[10], expert_performance=wages_data[11], medical_performance=wages_data[12], individual_performance=wages_data[13],
                                              parking_performance=wages_data[14], talent_performance=wages_data[15], public_performance=wages_data[16],
                                              deduction=wages_data[17], payable_performance=wages_data[18], personal_income_tax=wages_data[19], actual_performance=wages_data[20], deduction_remarks=wages_data[21],
                                              month=month, years=year)
                    items.append(Perfor_obj)
            except Exception as e:
                print(e)
                returnDict = {'code': 400, 'message': str(e)}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            PerformanceRecord.objects.bulk_create(items)
        returnDict = {'code': 200, 'message': 'ok'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ImportSalaryRecordListView(View):
    def get(self, request):
        user = request.user
        search_value = request.GET.get("search_value", None)
        # if search_value:
        #     objs = user.gatheringapply_set.all().order_by('-create_time')
        # else:
        objs = ImportSalaryRecord.objects.all().order_by('-create_time')

        paginator = Paginator(objs, 20)
        currentPage = int(request.GET.get("page", 1))

        if paginator.num_pages > 15:
            if currentPage - 5 < 1:
                pageRange = range(1, 11)
            elif currentPage + 5 > paginator.num_pages:
                pageRange = range(currentPage - 5, paginator.num_pages + 1)
            else:
                pageRange = range(currentPage - 5, currentPage + 5)
        else:
            pageRange = paginator.page_range

        try:
            objs_list = paginator.page(currentPage)
        except PageNotAnInteger:
            objs_list = paginator.page(1)
        except:
            objs_list = paginator.page(paginator.num_pages)

        context = {'objs': objs_list, 'realname': request.user.real_name, 'position': request.user.post,
                   "paginator": paginator,
                   "page_range": pageRange,  # 此处自定义一个分页段
                   "currentPage": currentPage, "search_value": search_value,
                   }
        if not search_value:
            context.pop("search_value")
        # 改为导入列表记录
        return render(request, 'finance/Excel_record.html', context)


class SalaryRecordListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        month_list, year_list = [], []
        objs = SalaryRecord.objects.all()
        if objs:
            check_year = objs.values("years").distinct()
            check_month = objs.values("month").distinct()
            for tt in check_month:
                month_list.append({'value': tt['month'], 'name': tt['month'] + "月"})
            for jj in check_year:
                year_list.append({'value': jj['years'], 'name': jj['years'] + "年"})

            SalaryObj = SalaryRecord.objects.filter(month=objs.last().month, years=objs.last().years)

            all_list = []
            for obj in SalaryObj:
                Performance_Obj = obj.user.performancerecord_set.filter(month=objs.last().month, years=objs.last().years)
                if not Performance_Obj:
                    one_dict = {"personnel_number": obj.personnel_number, "real_name": obj.real_name, "personnel_category": obj.personnel_category, "company": obj.company, "bank_account": obj.bank_account,
                                "post_wage": obj.post_wage, "salary_level_salary": obj.salary_level_salary, "standard_performance": obj.standard_performance, "protective_tape": obj.protective_tape, "car_tape": obj.car_tape,
                                "health_allowance": obj.health_allowance, "labor_insurance": obj.labor_insurance, "total_payable": obj.total_payable, "endowment_insurance": obj.endowment_insurance, "occupational_annuity": obj.occupational_annuity,
                                "medical_insurance": obj.medical_insurance, "unemployment_insurance": obj.unemployment_insurance, "housing_fund": obj.housing_fund, "deduction_insurance": obj.deduction_insurance, "deduction": obj.deduction,
                                "hydropower": obj.hydropower, "other": obj.other, "membership_fees": obj.membership_fees, "total_deduction": obj.total_deduction, "predict_amount": obj.predict_amount,
                                'Per_department_number': '', 'Per_department': "", 'Per_post': '', 'Per_category': '', 'Per_job_id': '',
                                'Per_names': '', 'Per_bank_number': '', 'Per_workload_performance': '', 'Per_management_performance': '', 'Per_night_performance': '',
                                'Per_consultation_performance': '', 'Per_expert_performance': '', 'Per_medical_performance': '', 'Per_individual_performance': '', 'Per_parking_performance': '',
                                'Per_talent_performance': '', 'Per_public_performance': '', 'Per_deduction': '', 'Per_payable_performance': '', 'Per_personal_income_tax': '',
                                'Per_actual_performance': '', 'Per_deduction_remarks': ''}
                else:
                    PerformanceObj = Performance_Obj
                    one_dict = {"personnel_number": obj.personnel_number, "real_name": obj.real_name,
                                "personnel_category": obj.personnel_category, "company": obj.company,
                                "bank_account": obj.bank_account,
                                "post_wage": obj.post_wage, "salary_level_salary": obj.salary_level_salary,
                                "standard_performance": obj.standard_performance,
                                "protective_tape": obj.protective_tape, "car_tape": obj.car_tape,
                                "health_allowance": obj.health_allowance, "labor_insurance": obj.labor_insurance,
                                "total_payable": obj.total_payable, "endowment_insurance": obj.endowment_insurance,
                                "occupational_annuity": obj.occupational_annuity,
                                "medical_insurance": obj.medical_insurance,
                                "unemployment_insurance": obj.unemployment_insurance, "housing_fund": obj.housing_fund,
                                "deduction_insurance": obj.deduction_insurance, "deduction": obj.deduction,
                                "hydropower": obj.hydropower, "other": obj.other,
                                "membership_fees": obj.membership_fees, "total_deduction": obj.total_deduction,
                                "predict_amount": obj.predict_amount,
                                'Per_department_number': PerformanceObj.department_number,
                                'Per_department': PerformanceObj.department, 'Per_post': PerformanceObj.post,
                                'Per_category': PerformanceObj.category, 'Per_job_id': PerformanceObj.job_id,
                                'Per_names': PerformanceObj.names, 'Per_bank_number': PerformanceObj.bank_number,
                                'Per_workload_performance': PerformanceObj.workload_performance,
                                'Per_management_performance': PerformanceObj.management_performance,
                                'Per_night_performance': PerformanceObj.night_performance,
                                'Per_consultation_performance': PerformanceObj.consultation_performance,
                                'Per_expert_performance': PerformanceObj.expert_performance,
                                'Per_medical_performance': PerformanceObj.medical_performance,
                                'Per_individual_performance': PerformanceObj.individual_performance,
                                'Per_parking_performance': PerformanceObj.parking_performance,
                                'Per_talent_performance': PerformanceObj.talent_performance,
                                'Per_public_performance': PerformanceObj.public_performance,
                                'Per_deduction': PerformanceObj.deduction,
                                'Per_payable_performance': PerformanceObj.payable_performance,
                                'Per_personal_income_tax': PerformanceObj.personal_income_tax,
                                'Per_actual_performance': PerformanceObj.actual_performance,
                                'Per_deduction_remarks': PerformanceObj.deduction_remarks}
                all_list.append(one_dict)
            context = {'realname': real_name, 'position': position, "month_list": month_list, "year_list": year_list, "department": department, "all_list": all_list}
            return render(request, 'finance/worker_bill_list.html', context)

        context = {'realname': real_name, 'position': position, "month_list": month_list, "year_list": year_list, "department": department}
        return render(request, 'finance/worker_bill_list.html', context)

    def post(self, request):
        months = request.POST.get("month", 1)
        years = request.POST.get("year", '')

        SalaryObj = SalaryRecord.objects.filter(month=months, years=years)

        all_list = []
        for obj in SalaryObj:
            Performance_Obj = obj.user.performancerecord_set.filter(month=months, years=years)
            if not Performance_Obj:
                one_dict = {"personnel_number": obj.personnel_number, "real_name": obj.real_name,
                            "personnel_category": obj.personnel_category, "company": obj.company,
                            "bank_account": obj.bank_account,
                            "post_wage": obj.post_wage, "salary_level_salary": obj.salary_level_salary,
                            "standard_performance": obj.standard_performance, "protective_tape": obj.protective_tape,
                            "car_tape": obj.car_tape,
                            "health_allowance": obj.health_allowance, "labor_insurance": obj.labor_insurance,
                            "total_payable": obj.total_payable, "endowment_insurance": obj.endowment_insurance,
                            "occupational_annuity": obj.occupational_annuity,
                            "medical_insurance": obj.medical_insurance,
                            "unemployment_insurance": obj.unemployment_insurance, "housing_fund": obj.housing_fund,
                            "deduction_insurance": obj.deduction_insurance, "deduction": obj.deduction,
                            "hydropower": obj.hydropower, "other": obj.other, "membership_fees": obj.membership_fees,
                            "total_deduction": obj.total_deduction, "predict_amount": obj.predict_amount,
                            'Per_department_number': '', 'Per_department': "", 'Per_post': '', 'Per_category': '',
                            'Per_job_id': '',
                            'Per_names': '', 'Per_bank_number': '', 'Per_workload_performance': '',
                            'Per_management_performance': '', 'Per_night_performance': '',
                            'Per_consultation_performance': '', 'Per_expert_performance': '',
                            'Per_medical_performance': '', 'Per_individual_performance': '',
                            'Per_parking_performance': '',
                            'Per_talent_performance': '', 'Per_public_performance': '', 'Per_deduction': '',
                            'Per_payable_performance': '', 'Per_personal_income_tax': '',
                            'Per_actual_performance': '', 'Per_deduction_remarks': ''}
            else:
                PerformanceObj = Performance_Obj
                one_dict = {"personnel_number": obj.personnel_number, "real_name": obj.real_name,
                            "personnel_category": obj.personnel_category, "company": obj.company,
                            "bank_account": obj.bank_account,
                            "post_wage": obj.post_wage, "salary_level_salary": obj.salary_level_salary,
                            "standard_performance": obj.standard_performance,
                            "protective_tape": obj.protective_tape, "car_tape": obj.car_tape,
                            "health_allowance": obj.health_allowance, "labor_insurance": obj.labor_insurance,
                            "total_payable": obj.total_payable, "endowment_insurance": obj.endowment_insurance,
                            "occupational_annuity": obj.occupational_annuity,
                            "medical_insurance": obj.medical_insurance,
                            "unemployment_insurance": obj.unemployment_insurance, "housing_fund": obj.housing_fund,
                            "deduction_insurance": obj.deduction_insurance, "deduction": obj.deduction,
                            "hydropower": obj.hydropower, "other": obj.other,
                            "membership_fees": obj.membership_fees, "total_deduction": obj.total_deduction,
                            "predict_amount": obj.predict_amount,
                            'Per_department_number': PerformanceObj.department_number,
                            'Per_department': PerformanceObj.department, 'Per_post': PerformanceObj.post,
                            'Per_category': PerformanceObj.category, 'Per_job_id': PerformanceObj.job_id,
                            'Per_names': PerformanceObj.names, 'Per_bank_number': PerformanceObj.bank_number,
                            'Per_workload_performance': PerformanceObj.workload_performance,
                            'Per_management_performance': PerformanceObj.management_performance,
                            'Per_night_performance': PerformanceObj.night_performance,
                            'Per_consultation_performance': PerformanceObj.consultation_performance,
                            'Per_expert_performance': PerformanceObj.expert_performance,
                            'Per_medical_performance': PerformanceObj.medical_performance,
                            'Per_individual_performance': PerformanceObj.individual_performance,
                            'Per_parking_performance': PerformanceObj.parking_performance,
                            'Per_talent_performance': PerformanceObj.talent_performance,
                            'Per_public_performance': PerformanceObj.public_performance,
                            'Per_deduction': PerformanceObj.deduction,
                            'Per_payable_performance': PerformanceObj.payable_performance,
                            'Per_personal_income_tax': PerformanceObj.personal_income_tax,
                            'Per_actual_performance': PerformanceObj.actual_performance,
                            'Per_deduction_remarks': PerformanceObj.deduction_remarks}
            all_list.append(one_dict)
        returnDict = {'code': 200, 'message': "查询成功！", "all_list": all_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SalaryRecordView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post}
        except:
            return redirect("/")
        # 改为薪酬创建页面
        return render(request, 'personal_center/gathering_apply_list.html', context)

    def post(self, request):
        user = request.POST.get('user', None)  # 孔智慧(8166)
        predict_amount = request.POST.get('predict_amount', None)
        actual_amount = request.POST.get('actual_amount', None)
        date = request.POST.get('date', None)  # 2022-10-26
        user = re.findall('\((.*?)\)', user)
        user_obj = User.objects.get(job_number=user[0])
        SalaryRecord.objects.create(user=user_obj, company=user_obj.company,
                                    job=user_obj.position,
                                    predict_amount=predict_amount,
                                    actual_amount=actual_amount,
                                    date=date)
        returnDict = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MySalaryRecordListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        month_list, year_list = [], []
        objs = SalaryRecord.objects.all()
        if objs:
            check_year = objs.values("years").distinct()
            check_month = objs.values("month").distinct()
            for tt in check_month:
                month_list.append({'value': tt['month'], 'name': tt['month'] + "月"})
            for jj in check_year:
                year_list.append({'value': jj['years'], 'name': jj['years'] + "年"})

            SalaryObj = SalaryRecord.objects.filter(month=objs.last().month, years=objs.last().years, user=request.user)

            all_list = []
            for obj in SalaryObj:
                Performance_Obj = obj.user.performancerecord_set.filter(month=objs.last().month, years=objs.last().years)
                if not Performance_Obj:
                    one_dict = {"personnel_number": obj.personnel_number, "real_name": obj.real_name,
                                "personnel_category": obj.personnel_category, "company": obj.company,
                                "bank_account": obj.bank_account,
                                "post_wage": obj.post_wage, "salary_level_salary": obj.salary_level_salary,
                                "standard_performance": obj.standard_performance,
                                "protective_tape": obj.protective_tape, "car_tape": obj.car_tape,
                                "health_allowance": obj.health_allowance, "labor_insurance": obj.labor_insurance,
                                "total_payable": obj.total_payable, "endowment_insurance": obj.endowment_insurance,
                                "occupational_annuity": obj.occupational_annuity,
                                "medical_insurance": obj.medical_insurance,
                                "unemployment_insurance": obj.unemployment_insurance, "housing_fund": obj.housing_fund,
                                "deduction_insurance": obj.deduction_insurance, "deduction": obj.deduction,
                                "hydropower": obj.hydropower, "other": obj.other,
                                "membership_fees": obj.membership_fees, "total_deduction": obj.total_deduction,
                                "predict_amount": obj.predict_amount,
                                'Per_department_number': '', 'Per_department': "", 'Per_post': '', 'Per_category': '',
                                'Per_job_id': '',
                                'Per_names': '', 'Per_bank_number': '', 'Per_workload_performance': '',
                                'Per_management_performance': '', 'Per_night_performance': '',
                                'Per_consultation_performance': '', 'Per_expert_performance': '',
                                'Per_medical_performance': '', 'Per_individual_performance': '',
                                'Per_parking_performance': '',
                                'Per_talent_performance': '', 'Per_public_performance': '', 'Per_deduction': '',
                                'Per_payable_performance': '', 'Per_personal_income_tax': '',
                                'Per_actual_performance': '', 'Per_deduction_remarks': ''}
                else:
                    PerformanceObj = Performance_Obj
                    one_dict = {"personnel_number": obj.personnel_number, "real_name": obj.real_name,
                                "personnel_category": obj.personnel_category, "company": obj.company,
                                "bank_account": obj.bank_account,
                                "post_wage": obj.post_wage, "salary_level_salary": obj.salary_level_salary,
                                "standard_performance": obj.standard_performance,
                                "protective_tape": obj.protective_tape, "car_tape": obj.car_tape,
                                "health_allowance": obj.health_allowance, "labor_insurance": obj.labor_insurance,
                                "total_payable": obj.total_payable, "endowment_insurance": obj.endowment_insurance,
                                "occupational_annuity": obj.occupational_annuity,
                                "medical_insurance": obj.medical_insurance,
                                "unemployment_insurance": obj.unemployment_insurance, "housing_fund": obj.housing_fund,
                                "deduction_insurance": obj.deduction_insurance, "deduction": obj.deduction,
                                "hydropower": obj.hydropower, "other": obj.other,
                                "membership_fees": obj.membership_fees, "total_deduction": obj.total_deduction,
                                "predict_amount": obj.predict_amount,
                                'Per_department_number': PerformanceObj.department_number,
                                'Per_department': PerformanceObj.department, 'Per_post': PerformanceObj.post,
                                'Per_category': PerformanceObj.category, 'Per_job_id': PerformanceObj.job_id,
                                'Per_names': PerformanceObj.names, 'Per_bank_number': PerformanceObj.bank_number,
                                'Per_workload_performance': PerformanceObj.workload_performance,
                                'Per_management_performance': PerformanceObj.management_performance,
                                'Per_night_performance': PerformanceObj.night_performance,
                                'Per_consultation_performance': PerformanceObj.consultation_performance,
                                'Per_expert_performance': PerformanceObj.expert_performance,
                                'Per_medical_performance': PerformanceObj.medical_performance,
                                'Per_individual_performance': PerformanceObj.individual_performance,
                                'Per_parking_performance': PerformanceObj.parking_performance,
                                'Per_talent_performance': PerformanceObj.talent_performance,
                                'Per_public_performance': PerformanceObj.public_performance,
                                'Per_deduction': PerformanceObj.deduction,
                                'Per_payable_performance': PerformanceObj.payable_performance,
                                'Per_personal_income_tax': PerformanceObj.personal_income_tax,
                                'Per_actual_performance': PerformanceObj.actual_performance,
                                'Per_deduction_remarks': PerformanceObj.deduction_remarks}
                all_list.append(one_dict)
            context = {'realname': real_name, 'position': position, "month_list": month_list, "year_list": year_list,
                       "department": department, "all_list": all_list}
            return render(request, 'finance/apply_for_reimbursement.html', context)

        context = {'realname': real_name, 'position': position, "month_list": month_list, "year_list": year_list,
                   "department": department}
        return render(request, 'finance/apply_for_reimbursement.html', context)

    def post(self, request):
        months = request.POST.get("month", 1)
        years = request.POST.get("year", '')

        SalaryObj = SalaryRecord.objects.filter(month=months, years=years, user=request.user)

        all_list = []
        for obj in SalaryObj:
            Performance_Obj = obj.user.performancerecord_set.filter(month=months, years=years)
            if not Performance_Obj:
                one_dict = {"personnel_number": obj.personnel_number, "real_name": obj.real_name,
                            "personnel_category": obj.personnel_category, "company": obj.company,
                            "bank_account": obj.bank_account,
                            "post_wage": obj.post_wage, "salary_level_salary": obj.salary_level_salary,
                            "standard_performance": obj.standard_performance, "protective_tape": obj.protective_tape,
                            "car_tape": obj.car_tape,
                            "health_allowance": obj.health_allowance, "labor_insurance": obj.labor_insurance,
                            "total_payable": obj.total_payable, "endowment_insurance": obj.endowment_insurance,
                            "occupational_annuity": obj.occupational_annuity,
                            "medical_insurance": obj.medical_insurance,
                            "unemployment_insurance": obj.unemployment_insurance, "housing_fund": obj.housing_fund,
                            "deduction_insurance": obj.deduction_insurance, "deduction": obj.deduction,
                            "hydropower": obj.hydropower, "other": obj.other, "membership_fees": obj.membership_fees,
                            "total_deduction": obj.total_deduction, "predict_amount": obj.predict_amount,
                            'Per_department_number': '', 'Per_department': "", 'Per_post': '', 'Per_category': '',
                            'Per_job_id': '',
                            'Per_names': '', 'Per_bank_number': '', 'Per_workload_performance': '',
                            'Per_management_performance': '', 'Per_night_performance': '',
                            'Per_consultation_performance': '', 'Per_expert_performance': '',
                            'Per_medical_performance': '', 'Per_individual_performance': '',
                            'Per_parking_performance': '',
                            'Per_talent_performance': '', 'Per_public_performance': '', 'Per_deduction': '',
                            'Per_payable_performance': '', 'Per_personal_income_tax': '',
                            'Per_actual_performance': '', 'Per_deduction_remarks': ''}
            else:
                PerformanceObj = Performance_Obj
                one_dict = {"personnel_number": obj.personnel_number, "real_name": obj.real_name,
                            "personnel_category": obj.personnel_category, "company": obj.company,
                            "bank_account": obj.bank_account,
                            "post_wage": obj.post_wage, "salary_level_salary": obj.salary_level_salary,
                            "standard_performance": obj.standard_performance,
                            "protective_tape": obj.protective_tape, "car_tape": obj.car_tape,
                            "health_allowance": obj.health_allowance, "labor_insurance": obj.labor_insurance,
                            "total_payable": obj.total_payable, "endowment_insurance": obj.endowment_insurance,
                            "occupational_annuity": obj.occupational_annuity,
                            "medical_insurance": obj.medical_insurance,
                            "unemployment_insurance": obj.unemployment_insurance, "housing_fund": obj.housing_fund,
                            "deduction_insurance": obj.deduction_insurance, "deduction": obj.deduction,
                            "hydropower": obj.hydropower, "other": obj.other,
                            "membership_fees": obj.membership_fees, "total_deduction": obj.total_deduction,
                            "predict_amount": obj.predict_amount,
                            'Per_department_number': PerformanceObj.department_number,
                            'Per_department': PerformanceObj.department, 'Per_post': PerformanceObj.post,
                            'Per_category': PerformanceObj.category, 'Per_job_id': PerformanceObj.job_id,
                            'Per_names': PerformanceObj.names, 'Per_bank_number': PerformanceObj.bank_number,
                            'Per_workload_performance': PerformanceObj.workload_performance,
                            'Per_management_performance': PerformanceObj.management_performance,
                            'Per_night_performance': PerformanceObj.night_performance,
                            'Per_consultation_performance': PerformanceObj.consultation_performance,
                            'Per_expert_performance': PerformanceObj.expert_performance,
                            'Per_medical_performance': PerformanceObj.medical_performance,
                            'Per_individual_performance': PerformanceObj.individual_performance,
                            'Per_parking_performance': PerformanceObj.parking_performance,
                            'Per_talent_performance': PerformanceObj.talent_performance,
                            'Per_public_performance': PerformanceObj.public_performance,
                            'Per_deduction': PerformanceObj.deduction,
                            'Per_payable_performance': PerformanceObj.payable_performance,
                            'Per_personal_income_tax': PerformanceObj.personal_income_tax,
                            'Per_actual_performance': PerformanceObj.actual_performance,
                            'Per_deduction_remarks': PerformanceObj.deduction_remarks}
            all_list.append(one_dict)
        returnDict = {'code': 200, 'message': "查询成功！", "all_list": all_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class CheckPasswordView(View):
    def post(self, request):
        password = request.POST.get('password', None)
        result = request.user.check_password(password)
        if not result:
            returnDict = {'code': 400, 'message': '密码不正确！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        request.session['password'] = password  # 设置session保存密码
        request.session.set_expiry(3600)  # 设置session过期时间
        returnDict = {'code': 200, 'message': 'ok！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ExportExcel(View):
    def get(self, request):
        user = request.user
        response = HttpResponse(content_type='application/ms-excel')
        response['Content-Disposition'] = 'attachment; filename="my_salary.xls"'
        wb = xlwt.Workbook(encoding='utf-8')
        ws = wb.add_sheet('Available Items')
        row_num = 0
        font_style = xlwt.XFStyle()
        font_style.font.bold = True
        columns = ['姓名', '科室', '职位', '日期', '应发工资', '实发工资']
        for col_num in range(len(columns)):
            ws.write(row_num, col_num, columns[col_num], font_style)
        font_style = xlwt.XFStyle()
        rows = user.salaryrecord_set.all().order_by('-create_time').values_list('user__real_name', 'company__name', 'job', 'date',
                                                       'predict_amount', 'actual_amount')
        # rows = [ for item in user.salaryrecord_set.all().order_by('-create_time')]
        for row in rows:
            row_num += 1
            for col_num in range(len(row)):
                gender = str(row[col_num])
                ws.write(row_num, col_num, gender, font_style)
        wb.save(response)
        return response


class TravelApplyListView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name, 'table_name': 'finance_travelapply'}
        except:
            return redirect("/")
        return render(request, 'finance/travel_apply_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = user.travelapply_set.all().order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'state': obj.state,
             'travel_type': obj.get_travel_type_display(),
             'start_time': obj.start_time.strftime("%Y-%m-%d") if type(obj.start_time) is not str else obj.start_time.split(" ")[0],
             'end_time': obj.end_time.strftime("%Y-%m-%d") if type(obj.end_time) is not str else obj.end_time.split(" ")[0],
             'subject': obj.subject,
             'route': obj.route,
             "url": f"<a href='travel_apply_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
             if obj.state == 'draft' else (f"<a href='travel_apply_detail_view?id={obj.id}'>查看</a> | <a href='travel_apply_detail_view?revise=true&id={obj.id}'>修改</a>"
             if obj.can_revise == '1' and obj.state in ['one', 'two', 'three', 'four']
             else (f"<a href='travel_apply_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
             if obj.state == 'stop' else f"<a href='travel_apply_detail_view?id={obj.id}'>查看</a>")),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TravelApplyIndexView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'uuid': uuid.uuid1()}
        except:
            return redirect("/")
        return render(request, 'finance/travel_apply_index.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        travel_type = request.POST.get('travel_type', None)
        checked_list = json.loads(request.POST.get('checked_list', None))
        start_time = request.POST.get('start_time', None)
        end_time = request.POST.get('end_time', None)
        route = request.POST.get('route', None)
        subject = request.POST.get('subject', None)
        travel_users = request.POST.get('travel_users', None)
        note = request.POST.get('note', '')
        fj_number = request.POST.get('uuid', None)
        xiugai = request.POST.get('xiugai', None)         # 是否是管理员修改
        revise = request.POST.get('revise', None)         # 是否是申请人修改
        start_time = datetime.strptime(start_time, '%Y-%m-%d')
        end_time = datetime.strptime(end_time, '%Y-%m-%d')

        travel_users = re.findall('\((.*?)\)', travel_users)
        travel_users_objs = User.objects.filter(job_number__in=travel_users)
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "差旅申请")
        except:
            pass
        if id:
            obj = TravelApply.objects.get(id=id)
            obj.travel_type = travel_type
            obj.start_time = start_time
            obj.end_time = end_time
            obj.route = route
            obj.subject = subject
            obj.note = note
            obj.save()

            if xiugai:
                message_str = "修改成功！"
            elif revise:
                message_str = "修改成功！"
                obj.travel_users.clear()
                obj.current_audit_users.clear()
                obj.travelapplyauditrecord_set.all().delete()
            else:
                message_str = '创建成功'
                obj.travel_users.clear()
        else:
            message_str = '创建成功'
            obj = TravelApply.objects.create(apply_user=request.user, company=request.user.company,
                                             travel_type=travel_type, user_type="", start_time=start_time,
                                             end_time=end_time, note=note, fj_number=fj_number, subject=subject, route=route, is_leader=False)
        if not xiugai:
            for travel_users_obj in travel_users_objs:
                obj.travel_users.add(travel_users_obj)

            person_charge = request.user.company.head_people
            flag = True
            if request.user != person_charge:
                TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=person_charge, audit_note='', state='unaudit', node='one')
                obj.current_audit_users.add(person_charge)
                obj.state = 'one'
                flag = False

            flag1 = True
            if travel_type == "one":
                six_people = Company.objects.get(id=14).head_people
                TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=six_people, audit_note='', state='unaudit', node='two')
                if flag:
                    obj.current_audit_users.add(six_people)
                    obj.state = 'two'
                    flag1 = False
            if travel_type == "two":
                six_people = Company.objects.get(id=13).head_people
                TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=six_people, audit_note='', state='unaudit', node='two')
                if flag:
                    obj.current_audit_users.add(six_people)
                    obj.state = 'two'
                    flag1 = False

            flag2 = True
            obj.ReportingDepartment.clear()
            if checked_list:
                if '3' in checked_list:
                    obj.ReportingDepartment.add(Company.objects.get(id=3))
                    nine_people = Company.objects.get(id=3).head_people
                    TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=nine_people, audit_note='', state='unaudit', node='three')
                    if flag and flag1:
                        obj.current_audit_users.add(nine_people)
                        obj.state = 'three'
                        flag2 = False

                if "15" in checked_list:
                    obj.ReportingDepartment.add(Company.objects.get(id=15))
                    seven_people = Company.objects.get(id=15).head_people
                    TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=seven_people, audit_note='', state='unaudit', node='three')
                    if flag and flag1:
                        obj.current_audit_users.add(seven_people)
                        obj.state = 'three'
                        flag2 = False

                # if travel_type != "two":
                if "13" in checked_list:
                    obj.ReportingDepartment.add(Company.objects.get(id=13))
                    six_people = Company.objects.get(id=13).head_people
                    TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=six_people, audit_note='', state='unaudit', node='three')
                    if flag and flag1:
                        obj.current_audit_users.add(six_people)
                        obj.state = 'three'
                        flag2 = False

            if request.user.company.id != 80:
                TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=request.user.company.leaders_id, audit_note='', state='unaudit', node='four')
                if flag and flag1 and flag2:
                    obj.current_audit_users.add(request.user.company.leaders_id)
                    obj.state = 'four'

            obj.save()
            message_str = '创建成功'
            if revise:
                message_str = "修改成功！"
            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "差旅申请"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.subject[:15] + "……" if len(obj.subject) > 15 else obj.subject
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
        returnDict = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TravelApplyDraftView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name}
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = TravelApply.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list, 'report_dep': [i.id for  i in obj.ReportingDepartment.all()]}
        return render(request, 'finance/travel_apply_draft_index.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        travel_type = request.POST.get('travel_type', None)
        start_time = request.POST.get('start_time', '')
        end_time = request.POST.get('end_time', '')
        route = request.POST.get('route', None)
        subject = request.POST.get('subject', None)
        travel_users = request.POST.get('travel_users', None)
        note = request.POST.get('note', '')
        fj_number = request.POST.get('uuid', None)
        checked_list = json.loads(request.POST.get('checked_list', None))
        if start_time:
            start_time = datetime.strptime(start_time, '%Y-%m-%d')
        if end_time:
            end_time = datetime.strptime(end_time, '%Y-%m-%d')

        travel_users = re.findall('\((.*?)\)', travel_users)
        travel_users_objs = User.objects.filter(job_number__in=travel_users)

        if id:
            obj = TravelApply.objects.get(id=id)
            obj.travel_type = travel_type
            obj.start_time = start_time
            obj.end_time = end_time
            obj.route = route
            obj.subject = subject
            obj.note = note
            obj.save()
            obj.travel_users.clear()
        else:
            obj = TravelApply.objects.create(apply_user=request.user, company=request.user.company, state='draft', travel_type=travel_type, user_type="", start_time=start_time,
                                             end_time=end_time, note=note, fj_number=fj_number, subject=subject, route=route, is_leader=False)
        for travel_users_obj in travel_users_objs:
            obj.travel_users.add(travel_users_obj)

        obj.ReportingDepartment.clear()
        for dep_id in checked_list:
            obj.ReportingDepartment.add(Company.objects.get(id=dep_id))

        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TravelApplyDetailView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name}
        except:
            return redirect("/")
        id = request.GET.get('id', None)

        if int(id) < 260:
            revise = request.GET.get('revise', '')
            obj = TravelApply.objects.get(id=id)
            audit_dic, flow_dict = {}, {}
            for audit_obj in obj.travelapplyauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                     os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

            one_step = obj.travelapplyauditrecord_set.filter(node='one')
            if one_step:
                apply_people = []
                apply = 'true'
                for obj_s in one_step:
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict['one'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            four_step = obj.travelapplyauditrecord_set.filter(node__in=['six', 'seven', 'eight', 'nine'])
            if four_step:
                apply_people = []
                apply = 'true'
                for obj_s in four_step:
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict['two'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                    'sear': len([i for i in flow_dict]) + 1}

            two_step = obj.travelapplyauditrecord_set.filter(node='two')
            if two_step:
                apply_people = []
                apply = 'true'
                for obj_s in two_step:
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict['three'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                      'sear': len([i for i in flow_dict]) + 1}

            three_step = obj.travelapplyauditrecord_set.filter(node='three')
            if three_step:
                apply_people = []
                apply = 'true'
                for obj_s in three_step:
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict['four'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                     'sear': len([i for i in flow_dict]) + 1}

            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                       "audit_dic": audit_dic,
                       "is_audit": "true" if obj.state in ['one', 'two', 'three', 'six', 'seven', 'eight',
                                                           'nine'] and request.user in obj.current_audit_users.all() else 'false',
                       "is_edit": "true" if (obj.state in [
                           'four'] and request.user == obj.apply_user) or revise else 'false',
                       "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'six', 'seven', 'eight',
                                                          'nine'] and request.user == obj.apply_user else 'false',
                       "flow_dict": flow_dict, "revise": revise,
                       "file_path": Topicsattachments.objects.filter(
                           topics_number=obj.fj_number).first().pdf_path.replace("\\",
                                                                                 "/") if Topicsattachments.objects.filter(
                           topics_number=obj.fj_number) else ""}
            return render(request, 'finance/travel_apply_detail_old.html', context)

        revise = request.GET.get('revise', '')
        obj = TravelApply.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.travelapplyauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        one_step = obj.travelapplyauditrecord_set.filter(node='one')
        if one_step:
            apply_people = []
            apply = 'true'
            for obj_s in one_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['one'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        four_step = obj.travelapplyauditrecord_set.filter(node='two')
        if four_step:
            apply_people = []
            apply = 'true'
            for obj_s in four_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['two'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        two_step = obj.travelapplyauditrecord_set.filter(node='three')
        if two_step:
            apply_people = []
            apply = 'true'
            for obj_s in two_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['three'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        three_step = obj.travelapplyauditrecord_set.filter(node='four')
        if three_step:
            apply_people = []
            apply = 'true'
            for obj_s in three_step:
                apply_people.append(obj_s.audit_people.real_name)
                if obj_s.state == "unaudit":
                    apply = 'false'
            flow_dict['four'] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}

        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['eight'] and request.user == obj.apply_user) or revise else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four'] and request.user == obj.apply_user else 'false',
                   "flow_dict": flow_dict, "revise": revise, 'report_dep': [i.id for  i in obj.ReportingDepartment.all()],
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""}
        return render(request, 'finance/travel_apply_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        obj = TravelApply.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "差旅申请")
        except:
            pass
        if int(id) < 260:
            if obj.state == 'one':
                obj.current_audit_users.clear()
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='one', audit_people=request.user).first()

                if state == 'audit':
                    countersign_list = obj.travelapplyauditrecord_set.filter(state='unaudit', node__in=['six', 'seven', 'eight', 'nine'])
                    if countersign_list.count():
                        obj_state = 'six'
                        for tt in countersign_list:
                            if audit_obj.audit_people != tt.audit_people:
                                obj.current_audit_users.add(tt.audit_people)
                            else:
                                tt.update_time = datetime.now()
                                tt.state = state
                                tt.audit_note = audit_note
                                tt.save()

                    else:
                        obj_state = 'two'
                        next_audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='two').first()
                        obj.current_audit_users.add(next_audit_obj.audit_people)
                    obj.state = obj_state
                    obj.save()
                else:
                    obj_state = 'four'
                    obj.state = obj_state
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()
                audit_obj.update_time = datetime.now()
                audit_obj.state = state
                audit_obj.audit_note = audit_note
                audit_obj.save()
                obj.can_revise = '0'
                obj.save()
                # ********************************************** 发送小程序推送 ******************************************
                topic_type = "差旅申请"
                applicant = obj.apply_user.real_name
                ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
                SubjectMatter = obj.subject[:15] + "……" if len(obj.subject) > 15 else obj.subject
                for jj in obj.current_audit_users.all():
                    try:
                        RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                returnDict = {'code': 200, 'message': '审核成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            elif obj.state == 'two':
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='two', audit_people=request.user).first()
                obj.current_audit_users.clear()
                if state == 'audit':
                    next_audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='three').first()
                    if next_audit_obj:
                        obj_state = 'three'
                        obj.current_audit_users.add(next_audit_obj.audit_people)
                    else:
                        obj_state = 'five'
                    obj.state = obj_state
                    obj.save()
                else:
                    obj_state = 'four'
                    obj.state = obj_state
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()
                audit_obj.update_time = datetime.now()
                audit_obj.state = state
                audit_obj.audit_note = audit_note
                audit_obj.save()
                obj.can_revise = '0'
                obj.save()
                # ********************************************** 发送小程序推送 ******************************************
                topic_type = "差旅申请"
                applicant = obj.apply_user.real_name
                ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
                SubjectMatter = obj.subject[:15] + "……" if len(obj.subject) > 15 else obj.subject
                for jj in obj.current_audit_users.all():
                    try:
                        RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                returnDict = {'code': 200, 'message': '审核成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            elif obj.state == 'three':
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='three', audit_people=request.user).first()
                obj.current_audit_users.clear()
                if state == 'audit':
                    obj.state = 'five'
                    obj.save()
                else:
                    obj_state = 'four'
                    obj.state = obj_state
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()
                audit_obj.update_time = datetime.now()
                audit_obj.state = state
                audit_obj.audit_note = audit_note
                audit_obj.save()
                obj.can_revise = '0'
                obj.save()
                returnDict = {'code': 200, 'message': '审核成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            elif obj.state in ['six', 'seven', 'eight', 'nine']:
                if state == 'audit':
                    if obj.current_audit_users.count() == 1:
                        obj.current_audit_users.clear()
                        obj.state = 'two'
                        obj.save()
                        next_audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='two').first()
                        obj.current_audit_users.add(next_audit_obj.audit_people)
                    else:
                        obj.current_audit_users.remove(request.user)
                else:
                    obj.state = 'four'
                    obj.current_audit_users.clear()
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()
                audit_list = obj.travelapplyauditrecord_set.filter(state='unaudit',
                                                                   node__in=['six', 'seven', 'eight', 'nine'])
                for ia in audit_list:
                    if ia.audit_people == request.user:
                        ia.update_time = datetime.now()
                        ia.state = state
                        ia.audit_note = audit_note
                        ia.save()
                obj.can_revise = '0'
                obj.save()
                # ********************************************** 发送小程序推送 ******************************************
                topic_type = "差旅申请"
                applicant = obj.apply_user.real_name
                ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
                SubjectMatter = obj.subject[:15] + "……" if len(obj.subject) > 15 else obj.subject
                for jj in obj.current_audit_users.all():
                    try:
                        RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                    except:
                        pass
                returnDict = {'code': 200, 'message': '审核成功'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            else:
                returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        else:
            if obj.state == 'one':
                obj.current_audit_users.clear()
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='one', audit_people=request.user).first()
                if state == 'audit':
                    two_step_list = obj.travelapplyauditrecord_set.filter(state='unaudit', node='two')
                    three_step_list = obj.travelapplyauditrecord_set.filter(state='unaudit', node='three')
                    if two_step_list:
                        obj_state = 'two'
                        for two_step in two_step_list:
                            obj.current_audit_users.add(two_step.audit_people)
                    elif three_step_list:
                        obj_state = 'three'
                        for three_step in three_step_list:
                            obj.current_audit_users.add(three_step.audit_people)
                    else:
                        obj_state = 'four'
                        next_audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='four').first()
                        obj.current_audit_users.add(next_audit_obj.audit_people)
                    obj.state = obj_state
                    obj.save()
                else:
                    obj.state = 'eight'
                    obj.current_audit_users.clear()
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()

            elif obj.state == 'two':
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='two', audit_people=request.user).first()
                obj.current_audit_users.clear()
                if state == 'audit':
                    three_step_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='three')
                    if three_step_obj:
                        obj_state = 'three'
                        for three_step in three_step_obj:
                            if three_step.audit_people == request.user:
                                three_step.update_time = datetime.now()
                                three_step.state = state
                                three_step.audit_note = audit_note
                                three_step.save()
                            else:
                                obj.current_audit_users.add(three_step.audit_people)

                        if not obj.travelapplyauditrecord_set.filter(state='unaudit', node='three'):
                            obj_state = 'four'
                            four_step_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='four').first()
                            obj.current_audit_users.add(four_step_obj.audit_people)

                    else:
                        obj_state = 'four'
                        four_step_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='four').first()
                        obj.current_audit_users.add(four_step_obj.audit_people)
                    obj.state = obj_state
                    obj.save()
                else:
                    obj.state = 'eight'
                    obj.current_audit_users.clear()
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()

            elif obj.state == 'three':
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='three', audit_people=request.user).first()
                if state == 'audit':
                    obj.current_audit_users.remove(request.user)
                    if obj.current_audit_users.all().count():
                        obj_state = 'three'
                    else:
                        if obj.travelapplyauditrecord_set.filter(state='unaudit', node='four'):
                            obj_state = 'four'
                            four_step_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='four').first()
                            obj.current_audit_users.add(four_step_obj.audit_people)
                        else:
                            obj_state = "five"
                            obj.save()
                    obj.state = obj_state
                    obj.save()
                else:
                    obj.state = 'eight'
                    obj.current_audit_users.clear()
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()

            elif obj.state == 'four':
                audit_obj = obj.travelapplyauditrecord_set.filter(state='unaudit', node='four', audit_people=request.user).first()
                obj.current_audit_users.clear()
                if state == 'audit':
                    obj.state = "five"
                    obj.save()
                    MakeCopy.objects.create(recipient=Company.objects.get(id=16).head_people, process_id=obj.id, type='m')
                else:
                    obj.state = 'eight'
                    obj.current_audit_users.add(obj.apply_user)
                    obj.save()

            else:
                returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            audit_obj.update_time = datetime.now()
            audit_obj.state = state
            audit_obj.audit_note = audit_note
            audit_obj.save()
            obj.can_revise = '0'
            obj.save()
            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "差旅申请"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.subject[:15] + "……" if len(obj.subject) > 15 else obj.subject
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
            returnDict = {'code': 200, 'message': '审核成功'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TravelApplyRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = TravelApply.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'five':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的差旅申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.travelapplyauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的差旅申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'five':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的差旅申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class TravelApplyWriteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = TravelApply.objects.get(id=int(id))
        # if obj.state != 'eight':
        #     returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
        #     return HttpResponse(json.dumps(returnData), content_type="application/json")

        travel_type = request.POST.get('travel_type', None)
        checked_list = json.loads(request.POST.get('checked_list', None))
        start_time = request.POST.get('start_time', None)
        end_time = request.POST.get('end_time', None)
        route = request.POST.get('route', None)
        subject = request.POST.get('subject', None)
        travel_users = request.POST.get('travel_users', None)
        note = request.POST.get('note', '')
        start_time = datetime.strptime(start_time, '%Y-%m-%d')
        end_time = datetime.strptime(end_time, '%Y-%m-%d')

        travel_users = re.findall('\((.*?)\)', travel_users)
        travel_users_objs = User.objects.filter(job_number__in=travel_users)

        obj.travel_type = travel_type
        obj.start_time = start_time
        obj.end_time = end_time
        obj.route = route
        obj.subject = subject
        obj.note = note
        obj.save()
        obj.travel_users.clear()
        for travel_users_obj in travel_users_objs:
            obj.travel_users.add(travel_users_obj)

        obj.current_audit_users.clear()
        obj.travelapplyauditrecord_set.filter(state='unaudit').delete()

        for travel_users_obj in travel_users_objs:
            obj.travel_users.add(travel_users_obj)

        if int(id) > 260:
            person_charge = request.user.company.head_people
            flag = True
            if request.user != person_charge:
                TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=person_charge, audit_note='', state='unaudit', node='one')
                obj.current_audit_users.add(person_charge)
                obj.state = 'one'
                flag = False

            flag1 = True
            if travel_type == "one":
                obj.ReportingDepartment.add(Company.objects.get(id=14))
                six_people = Company.objects.get(id=14).head_people
                TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=six_people, audit_note='', state='unaudit', node='two')
                if flag:
                    obj.current_audit_users.add(six_people)
                    obj.state = 'two'
                    flag1 = False
            if travel_type == "two":
                obj.ReportingDepartment.add(Company.objects.get(id=13))
                six_people = Company.objects.get(id=13).head_people
                TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=six_people, audit_note='', state='unaudit', node='two')
                if flag:
                    obj.current_audit_users.add(six_people)
                    obj.state = 'two'
                    flag1 = False

            flag2 = True
            if checked_list:
                if '3' in checked_list:
                    obj.ReportingDepartment.add(Company.objects.get(id=3))
                    nine_people = Company.objects.get(id=3).head_people
                    TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=nine_people, audit_note='', state='unaudit', node='three')
                    if flag and flag1:
                        obj.current_audit_users.add(nine_people)
                        obj.state = 'three'
                        flag2 = False
                if "15" in checked_list:
                    obj.ReportingDepartment.add(Company.objects.get(id=15))
                    seven_people = Company.objects.get(id=15).head_people
                    TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=seven_people, audit_note='', state='unaudit', node='three')
                    if flag and flag1:
                        obj.current_audit_users.add(seven_people)
                        obj.state = 'three'
                        flag2 = False
                if travel_type != "two":
                    if "13" in checked_list:
                        obj.ReportingDepartment.add(Company.objects.get(id=13))
                        six_people = Company.objects.get(id=13).head_people
                        TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=six_people, audit_note='', state='unaudit', node='three')
                        if flag and flag1:
                            obj.current_audit_users.add(six_people)
                            obj.state = 'three'
                            flag2 = False

                TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=request.user.company.leaders_id, audit_note='', state='unaudit', node='four')
                if flag and flag1 and flag2:
                    obj.current_audit_users.add(request.user.company.leaders_id)
                    obj.state = 'four'

            obj.save()
            returnDict = {'code': 200, 'message': "修改成功！"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        else:
            leaders_flag = False
            for travel_users_obj in travel_users_objs:
                obj.travel_users.add(travel_users_obj)
                if travel_users_obj.group.id in [1, 2, 3, 4]:
                    leaders_flag = True

            person_charge = request.user.company.head_people
            flag = True
            if request.user != person_charge:
                TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=person_charge, audit_note='', state='unaudit', node='one')
                obj.current_audit_users.add(person_charge)
                obj.state = 'one'
                flag = False
            flag1 = True
            if checked_list:
                flag1 = False
                if '3' in checked_list:
                    obj.ReportingDepartment.add(Company.objects.get(id=3))
                    nine_people = Company.objects.get(id=3).head_people
                    TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=nine_people, audit_note='', state='unaudit', node='nine')
                    if flag:
                        obj.current_audit_users.add(nine_people)
                        obj.state = 'six'
                if '13' in checked_list:
                    obj.ReportingDepartment.add(Company.objects.get(id=13))
                    eight_people = Company.objects.get(id=13).head_people
                    TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=eight_people, audit_note='', state='unaudit', node='eight')
                    if flag:
                        obj.current_audit_users.add(eight_people)
                        obj.state = 'six'
                if "14" in checked_list:
                    obj.ReportingDepartment.add(Company.objects.get(id=14))
                    six_people = Company.objects.get(id=14).head_people
                    TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=six_people, audit_note='', state='unaudit', node='six')
                    if flag:
                        obj.current_audit_users.add(six_people)
                        obj.state = 'six'
                if "15" in checked_list:
                    obj.ReportingDepartment.add(Company.objects.get(id=15))
                    seven_people = Company.objects.get(id=15).head_people
                    TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=seven_people, audit_note='', state='unaudit', node='seven')
                    if flag:
                        obj.current_audit_users.add(seven_people)
                        obj.state = 'six'
            TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=request.user.company.leaders_id, audit_note='', state='unaudit', node='two')

            if leaders_flag:
                TravelApplyAuditRecord.objects.create(parent_id=obj, audit_people=Staffing.objects.get(station='差旅报备领导').post_personnel.all().first(), audit_note='', state='unaudit', node='three')
            if flag and flag1:
                obj.current_audit_users.add(request.user.company.leaders_id)
                obj.state = 'two'
            obj.save()
            message_str = '修改成功'
            returnDict = {'code': 200, 'message': message_str}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MedicalMaterialsListView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, "table_name": "finance_medicalmaterials"}
        except:
            return redirect("/")
        return render(request, 'finance/medical_materials_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = user.medicalmaterials_set.all().order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'title': obj.title,
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'total_amount': obj.total_amount,
             'source': obj.source,
             "url": f"<a href='medical_materials_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
             if obj.state == 'draft'
             else (f"<a href='medical_materials_detail_view?id={obj.id}'>查看</a>" if obj.state != "stop" else
                   f"<a href='medical_materials_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MedicalMaterialsIndexView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, "uuid": uuid.uuid1()}
        except:
            return redirect("/")
        return render(request, 'finance/medical_materials_index.html', context)

    def post(self, request):
        # user = request.user
        # id = request.POST.get('id', None)
        # title = request.POST.get('title', None)                             # 付款事由
        # total_amount = request.POST.get('total_amount', None)               # 总金额
        # source = request.POST.get('source', None)                           # 经费来源
        # fj_number = request.POST.get('uuid', None)
        # detail_pay = request.POST.get('detail_pay', None)                   # 付款明细
        # AuditAccounting = request.POST.get('AuditAccounting', None)         # 审核会计
        # remake = request.POST.get('remake', None)                           # 备注
        # daxie = request.POST.get('daxie', None)                             # 大写
        # payee = request.POST.get('payee', '')
        # payee_account = request.POST.get('payee_account', '')
        # # ************************************************ 保存操作记录 ************************************
        # try:
        #     RecordAndPush().OperationRecords(request, "材料付款")
        # except:
        #     pass
        # state = 'one'
        # cwk_obj = Company.objects.get(id=23)
        # clkj_obj = User.objects.get(id=int(AuditAccounting))
        # try:
        #     yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
        # except Exception as e:
        #     returnDict = {'code': 500, 'message': '院长岗位未维护，请联系管理员维护'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # try:
        #     sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
        # except Exception as e:
        #     returnDict = {'code': 500, 'message': '书记岗位未维护，请联系管理员维护'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # try:
        #     gh_obj = Staffing.objects.get(station='工会主席').post_personnel.all().first()
        # except Exception as e:
        #     returnDict = {'code': 500, 'message': '工会主席岗位未维护，请联系管理员维护'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # try:
        #     cwzf_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        # except Exception as e:
        #     returnDict = {'code': 500, 'message': '财务支付岗位未维护，请联系管理员维护'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # if id:
        #     obj = MedicalMaterials.objects.get(id=id)
        #     obj.title = title
        #     obj.total_amount = total_amount
        #     obj.accounting = f"{clkj_obj.real_name}({clkj_obj.id})"
        #     obj.source = source
        #     obj.detail_pay = detail_pay
        #     obj.daxie = daxie
        #     obj.remake = remake
        #     obj.payee = payee
        #     obj.payee_account = payee_account
        #     obj.state = state
        #     obj.save()
        # else:
        #     obj = MedicalMaterials.objects.create(apply_user=request.user, company=request.user.company, state=state, accounting = f"{clkj_obj.real_name}({clkj_obj.id})",
        #                                      title=title, total_amount=total_amount, source=source, fj_number=fj_number,
        #                                           detail_pay=detail_pay, daxie=daxie, remake=remake, payee=payee, payee_account=payee_account)
        #
        # total_amount = float(total_amount.replace(",", ''))
        #
        # cwk_director = cwk_obj.head_people                                             # 财务科负责人
        # one_audit_people = request.user.company.head_people
        #
        # MedicalMaterialsAuditRecord.objects.create(parent_id=obj, audit_people=clkj_obj, audit_note='', state='unaudit', node='two')
        # obj.current_audit_users.add(clkj_obj)
        # obj.state = "two"
        # obj.save()
        # if user != one_audit_people:
        #     MedicalMaterialsAuditRecord.objects.create(parent_id=obj, audit_people=one_audit_people, audit_note='', state='unaudit', node='one')
        # MedicalMaterialsAuditRecord.objects.create(parent_id=obj, audit_people=cwk_director, audit_note='', state='unaudit', node='three')
        # MedicalMaterialsAuditRecord.objects.create(parent_id=obj, audit_people=request.user.company.leaders_id, audit_note='', state='unaudit', node='four')
        # MedicalMaterialsAuditRecord.objects.create(parent_id=obj, audit_people=sj_obj if total_amount >= 200000 else yz_obj if 200000 > total_amount >= 10000 else gh_obj, audit_note='', state='unaudit', node='five')
        # MedicalMaterialsAuditRecord.objects.create(parent_id=obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')
        # # ********************************************** 发送小程序推送 ******************************************
        # topic_type = "材料付款"
        # applicant = obj.apply_user.real_name
        # ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        # SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        # for jj in obj.current_audit_users.all():
        #     try:
        #         RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        #     except:
        #         pass
        # returnDict = {'code': 200, 'message': '创建成功'}
        returnDict = {'code': 200, 'message': '该流程已关闭，现已无法申请！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MedicalMaterialsDraftView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name}
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = MedicalMaterials.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list, "detail_pay": json.loads(obj.detail_pay)}
        return render(request, 'finance/medical_materials_draft.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        title = request.POST.get('title', None)  # 付款事由
        total_amount = request.POST.get('total_amount', 0)  # 总金额
        source = request.POST.get('source', None)  # 经费来源
        fj_number = request.POST.get('uuid', None)
        detail_pay = request.POST.get('detail_pay', None)  # 付款明细
        AuditAccounting = request.POST.get('AuditAccounting', None)  # 审核会计
        remake = request.POST.get('remake', None)  # 备注
        daxie = request.POST.get('daxie', None)  # 大写
        payee = request.POST.get('payee', '')
        payee_account = request.POST.get('payee_account', '')
        state = 'draft'
        if id:
            obj = MedicalMaterials.objects.get(id=id)
            obj.title = title
            obj.total_amount = total_amount
            obj.source = source
            obj.detail_pay = detail_pay
            obj.accounting = f"{User.objects.get(id=int(AuditAccounting)).real_name}({User.objects.get(id=int(AuditAccounting)).id})" if AuditAccounting else ""
            obj.daxie = daxie
            obj.remake = remake
            obj.payee = payee
            obj.payee_account = payee_account
            obj.state = state
            obj.save()
        else:
            obj = MedicalMaterials.objects.create(apply_user=request.user, company=request.user.company, state=state,
                                                  title=title, total_amount=total_amount, source=source,
                                                  fj_number=fj_number, accounting = f"{User.objects.get(id=int(AuditAccounting)).real_name}({User.objects.get(id=int(AuditAccounting)).id})" if AuditAccounting != '0' else "",
                                                  detail_pay=detail_pay, daxie=daxie, remake=remake,payee=payee, payee_account=payee_account)

        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MedicalMaterialsDetailView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name}
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = MedicalMaterials.objects.get(id=id)
        fujian_obj = Topicsattachments.objects.filter(topics_number=obj.fj_number)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.medicalmaterialsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.medicalmaterialsauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in fujian_obj]
        # record_file_list = [atta_obj.pdf_path.replace("\\", "/") for atta_obj in Topicsattachments.objects.filter(topics_number=obj.medicalmaterialsauditrecord_set.get(node='six').audit_note)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if obj.state in ['eight'] and request.user == obj.apply_user else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false',
                   "record_uuid": uuid.uuid1(),
                   # "record_file_list": record_file_list,
                   "detail_pay": json.loads(obj.detail_pay),
                   'file_path': fujian_obj.first().pdf_path.replace("\\", "/") if fujian_obj else "",
                   'flow_dict': flow_dict
                   }
        return render(request, 'finance/medical_materials_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "材料付款")
        except:
            pass
        obj = MedicalMaterials.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.medicalmaterialsauditrecord_set.filter(node='one', state='unaudit'):
                    next_audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='one', state='unaudit').first()
                    obj_state = 'one'
                else:
                    next_audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'three':
            audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'eight'
        elif obj.state == 'four':
            audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
            else:
                obj_state = 'eight'
        elif obj.state == 'five':
            audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='six', state='unaudit').first()
                obj_state = 'six'
            else:
                obj_state = 'eight'
        elif obj.state == 'six':
            audit_obj = obj.medicalmaterialsauditrecord_set.filter(node='six', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "材料付款"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MedicalMaterialsRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = MedicalMaterials.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的付款申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.medicalmaterialsauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的付款申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的付款申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class MedicalMaterialsWriteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        title = request.POST.get('title', None)  # 付款事由
        total_amount = request.POST.get('total_amount', 0)  # 总金额
        source = request.POST.get('source', None)  # 经费来源
        detail_pay = request.POST.get('detail_pay', None)  # 付款明细
        AuditAccounting = request.POST.get('AuditAccounting', None)  # 审核会计
        remake = request.POST.get('remake', None)  # 备注
        daxie = request.POST.get('daxie', None)  # 大写
        xiugai = request.POST.get('xiugai', None)  # 管理员修改
        payee = request.POST.get('payee', '')
        payee_account = request.POST.get('payee_account', '')
        obj = MedicalMaterials.objects.get(id=int(id))

        if obj.state != 'eight' and not xiugai:
            returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.title = title
        obj.total_amount = total_amount
        obj.source = source
        obj.detail_pay = detail_pay
        obj.remake = remake
        obj.daxie = daxie
        obj.payee = payee
        obj.payee_account = payee_account
        obj.state = 'one'
        obj.save()
        if xiugai:
            returnData = {'code': 200, 'message': '修改成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.current_audit_users.clear()
        obj.medicalmaterialsauditrecord_set.filter(state="unaudit").delete()

        yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
        sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
        gh_obj = Company.objects.get(id=23).leaders_id
        cwzf_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()

        clkj_obj = User.objects.get(id=int(AuditAccounting))

        total_amount = float(total_amount.replace(",", ''))
        cwk_obj = Company.objects.get(id=23)
        cwk_director = cwk_obj.head_people                                            # 财务科负责人
        one_audit_people = request.user.company.head_people

        MedicalMaterialsAuditRecord.objects.create(parent_id=obj, audit_people=clkj_obj, audit_note='', state='unaudit', node='two')
        obj.current_audit_users.add(clkj_obj)
        obj.state = "two"
        obj.save()
        if request.user != one_audit_people:
            MedicalMaterialsAuditRecord.objects.create(parent_id=obj, audit_people=one_audit_people, audit_note='', state='unaudit', node='one')
        MedicalMaterialsAuditRecord.objects.create(parent_id=obj, audit_people=cwk_director, audit_note='', state='unaudit', node='three')
        MedicalMaterialsAuditRecord.objects.create(parent_id=obj, audit_people=request.user.company.leaders_id, audit_note='', state='unaudit', node='four')
        MedicalMaterialsAuditRecord.objects.create(parent_id=obj, audit_people=sj_obj if total_amount >= 200000 else yz_obj if 200000 > total_amount >= 10000 else gh_obj,
                                                   audit_note='', state='unaudit', node='five')
        MedicalMaterialsAuditRecord.objects.create(parent_id=obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')

        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class GeneralFinanceListView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, 'table_name': "finance_generalfinance"}
        except:
            return redirect("/")
        return render(request, 'finance/general_finance_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = GeneralFinance.objects.filter(apply_user=request.user).order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'title': obj.title,
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'total_amount': obj.total_amount,
             "url": f"<a href='general_finance_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
             if obj.state == 'draft' else (f"<a href='general_finance_detail_view?id={obj.id}'>查看</a> | <a href='general_finance_detail_view?revise=true&id={obj.id}'>修改</a>"
                                           if obj.can_revise == '1' and obj.state in ['one', 'two', 'three']
                                           else (f"<a href='general_finance_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                                                 if obj.state == 'stop' else f"<a href='general_finance_detail_view?id={obj.id}'>查看</a>")),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GeneralFinanceIndexView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, 'uuid': uuid.uuid1()}
        except:
            return redirect("/")
        leaders_obj= User.objects.filter(group_id=2)
        context["leaders_obj"] = leaders_obj
        return render(request, 'finance/general_finance_index.html', context)

    def post(self, request):
        # user = request.user
        # id = request.POST.get('id', None)
        # title = request.POST.get('title', None)
        # total_amount = request.POST.get('total_amount', None)
        # detail_pay = request.POST.get('detail_pay', None)
        # daxie = request.POST.get('daxie', None)
        # fj_number = request.POST.get('uuid', None)
        # remake = request.POST.get('remake', '')
        # revise = request.POST.get('revise', None)
        # payee = request.POST.get('payee', '')
        # payee_account = request.POST.get('payee_account', '')
        # ApprovalLeader = request.POST.get('ApprovalLeader', '')
        # # ************************************************ 保存操作记录 ************************************
        # try:
        #     RecordAndPush().OperationRecords(request, "一般付款")
        # except:
        #     pass
        # if ApprovalLeader:
        #     three_appave = User.objects.get(id=ApprovalLeader)
        # else:
        #     three_appave = user.company.leaders_id
        # state = 'one'
        #
        # cwk_obj = Company.objects.get(id=23)
        #
        # try:
        #     yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
        # except Exception as e:
        #     returnDict = {'code': 500, 'message': '院长岗位未维护，请联系管理员维护'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # try:
        #     sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
        # except Exception as e:
        #     returnDict = {'code': 500, 'message': '书记岗位未维护，请联系管理员维护'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # try:
        #     gh_obj = Staffing.objects.get(station='工会主席').post_personnel.all().first()
        # except Exception as e:
        #     returnDict = {'code': 500, 'message': '工会主席岗位未维护，请联系管理员维护'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # try:
        #     cwzf_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        # except Exception as e:
        #     returnDict = {'code': 500, 'message': '财务支付岗位未维护，请联系管理员维护'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # if id:
        #     obj = GeneralFinance.objects.get(id=id)
        #     obj.title = title
        #     obj.total_amount = total_amount
        #     obj.quantity = 0
        #     obj.remake = remake
        #     obj.leader = three_appave
        #     obj.price = 0
        #     obj.daxie = daxie
        #     obj.detail_pay = json.dumps(detail_pay)
        #     obj.payee = payee
        #     obj.payee_account = payee_account
        #     obj.state = state
        #     obj.save()
        #     if revise:
        #         obj.current_audit_users.clear()
        #         obj.generalfinanceauditrecord_set.all().delete()
        # else:
        #     obj = GeneralFinance.objects.create(apply_user=request.user, company=request.user.company, state=state, remake=remake,
        #                                         title=title, total_amount=total_amount, quantity=0, price=0, leader=three_appave,
        #                                         fj_number=fj_number, daxie=daxie, detail_pay=json.dumps(detail_pay),payee_account=payee_account, payee=payee)
        # total_amount = float(total_amount.replace(",", ""))
        # one_appave = user.company.head_people
        # flag = True
        # if user != one_appave:
        #     GeneralFinanceAuditRecord.objects.create(parent_id=obj, audit_people=one_appave, audit_note='', state='unaudit', node='one')
        #     obj.current_audit_users.add(one_appave)
        #     obj.state = 'one'
        #     obj.save()
        #     flag = False
        #
        # two_appave = cwk_obj.head_people
        # GeneralFinanceAuditRecord.objects.create(parent_id=obj, audit_people=three_appave, audit_note='', state='unaudit', node='three')
        # if flag:
        #     obj.current_audit_users.add(three_appave)
        #     obj.state = 'three'
        #     obj.save()
        # GeneralFinanceAuditRecord.objects.create(parent_id=obj, audit_people=two_appave, audit_note='', state='unaudit', node='two')
        # GeneralFinanceAuditRecord.objects.create(parent_id=obj, audit_people=[[yz_obj, sj_obj][total_amount >= 200000], gh_obj][total_amount < 10000], audit_note='', state='unaudit', node='four')
        # GeneralFinanceAuditRecord.objects.create(parent_id=obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='five')
        # # ********************************************** 发送小程序推送 ******************************************
        # topic_type = "一般付款"
        # applicant = obj.apply_user.real_name
        # ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        # SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        # for jj in obj.current_audit_users.all():
        #     try:
        #         RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        #     except:
        #         pass
        # returnDict = {'code': 200, 'message': '创建成功'}
        returnDict = {'code': 400, 'message': '该流程已关闭，现已无法申请！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GeneralFinanceDraftView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name}
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = GeneralFinance.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        leaders_obj = User.objects.filter(group_id=2)
        context = {'realname': request.user.real_name, 'position': request.user.post, "leaders_obj": leaders_obj,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list, "detail_pay": json.loads(json.loads(obj.detail_pay))}
        return render(request, 'finance/general_finance_draft.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        title = request.POST.get('title', '')
        total_amount = request.POST.get('total_amount', None)
        detail_pay = request.POST.get('detail_pay', None)
        daxie = request.POST.get('daxie', None)
        fj_number = request.POST.get('uuid', None)
        payee = request.POST.get('payee', '')
        payee_account = request.POST.get('payee_account', '')
        remake = request.POST.get('remake', '')
        ApprovalLeader = request.POST.get('ApprovalLeader', '')
        if ApprovalLeader != "0":
            leaders = User.objects.get(id=ApprovalLeader)
        else:
            leaders = None
        state = 'draft'
        if id:
            obj = GeneralFinance.objects.get(id=id)
            obj.title = title
            obj.total_amount = total_amount
            obj.quantity = 0
            obj.remake = remake
            obj.price = 0
            obj.daxie = daxie
            obj.detail_pay = json.dumps(detail_pay)
            obj.state = state
            obj.payee = payee
            obj.payee_account = payee_account
            if leaders:
                obj.leader = leaders
            obj.save()
        else:
            if leaders:
                obj = GeneralFinance.objects.create(apply_user=request.user, company=request.user.company, state=state, remake=remake,
                                                title=title, total_amount=total_amount, quantity=0, price=0, leader=leaders,
                                                fj_number=fj_number, daxie=daxie, detail_pay=json.dumps(detail_pay), payee=payee,payee_account=payee_account)
            else:
                obj = GeneralFinance.objects.create(apply_user=request.user, company=request.user.company, state=state,
                                                    remake=remake,
                                                    title=title, total_amount=total_amount, quantity=0, price=0,
                                                    fj_number=fj_number, daxie=daxie, detail_pay=json.dumps(detail_pay),
                                                    payee=payee, payee_account=payee_account)
        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GeneralFinanceDetailView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name}
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = GeneralFinance.objects.get(id=id)
        revise = request.GET.get('revise', None)
        fujian_obj = Topicsattachments.objects.filter(topics_number=obj.fj_number)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.generalfinanceauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.generalfinanceauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in fujian_obj]
        leaders_obj = User.objects.filter(group_id=2)
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "detail_pay": json.loads(json.loads(obj.detail_pay)),
                   "audit_dic": audit_dic, "leaders_obj": leaders_obj,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['eight'] and request.user == obj.apply_user) or revise else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'eight'] and request.user == obj.apply_user else 'false',
                   'file_path': fujian_obj.first().pdf_path.replace("\\", "/") if fujian_obj else "",
                   'flow_dict': flow_dict, "revise": revise
                   }
        return render(request, 'finance/general_finance_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "一般付款")
        except:
            pass
        obj = GeneralFinance.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.generalfinanceauditrecord_set.filter(node='one', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.generalfinanceauditrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.generalfinanceauditrecord_set.filter(node='two', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.generalfinanceauditrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'eight'
        elif obj.state == 'three':
            audit_obj = obj.generalfinanceauditrecord_set.filter(node='three', state='unaudit',
                                                                   audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.generalfinanceauditrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'eight'
        elif obj.state == 'four':
            audit_obj = obj.generalfinanceauditrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.generalfinanceauditrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
            else:
                obj_state = 'eight'
        elif obj.state == 'five':
            audit_obj = obj.generalfinanceauditrecord_set.filter(node='five', state='unaudit',  audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        obj.can_revise = '0'
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "一般付款"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class GeneralFinanceRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = GeneralFinance.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的付款申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.generalfinanceauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的付款申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的付款申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class GeneralFinanceWriteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        title = request.POST.get('title', None)
        total_amount = request.POST.get('total_amount', None)
        detail_pay = request.POST.get('detail_pay', None)
        daxie = request.POST.get('daxie', None)
        remake = request.POST.get('remake', '')
        xiugai = request.POST.get('xiugai', None)
        payee = request.POST.get('payee', '')
        payee_account = request.POST.get('payee_account', '')
        obj = GeneralFinance.objects.get(id=int(id))
        if obj.state != 'eight' and not xiugai:
            returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.title = title
        obj.total_amount = total_amount
        obj.quantity = 0
        obj.remake = remake
        obj.price = 0
        obj.daxie = daxie
        obj.detail_pay = json.dumps(detail_pay)
        obj.payee = payee
        obj.payee_account = payee_account
        obj.save()

        if not xiugai:
            obj.current_audit_users.clear()
            cwk_obj = Company.objects.get(id=23)
            flag = True
            if obj.generalfinanceauditrecord_set.filter(node='one'):
                if obj.generalfinanceauditrecord_set.filter(node='one', state='unaudit').count() == 0:
                    audit_record_obj = obj.generalfinanceauditrecord_set.filter(node='one').first()
                    GeneralFinanceAuditRecord.objects.create(node='one', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)
                    obj.current_audit_users.add(audit_record_obj.audit_people)
                    obj.state = 'one'
                    obj.save()
                    flag = False

            if obj.generalfinanceauditrecord_set.filter(node='two', state='unaudit').count() == 0:
                audit_record_obj = obj.generalfinanceauditrecord_set.filter(node='two').first()
                GeneralFinanceAuditRecord.objects.create(node='two', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

            audit_record_obj = obj.generalfinanceauditrecord_set.filter(node='three').first()
            if obj.generalfinanceauditrecord_set.filter(node='three', state='unaudit').count() == 0:
                GeneralFinanceAuditRecord.objects.create(node='three', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)
            if flag:
                obj.current_audit_users.add(audit_record_obj.audit_people)
                obj.state = 'three'
                obj.save()

            obj.generalfinanceauditrecord_set.filter(node='four', state='unaudit').delete()
            yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
            sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
            total_amount = float(total_amount.replace(',', ''))
            GeneralFinanceAuditRecord.objects.create(parent_id=obj, audit_people=[[yz_obj, sj_obj][total_amount >= 200000], cwk_obj.leaders_id][total_amount < 10000], audit_note='', state='unaudit', node='four')

            if obj.generalfinanceauditrecord_set.filter(node='five', state='unaudit').count() == 0:
                audit_record_obj = obj.generalfinanceauditrecord_set.filter(node='five').first()
                GeneralFinanceAuditRecord.objects.create(node='five', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)

        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class NutritionalMealsListView(View):
    def get(self, request):
        try:
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, "table_name": "finance_nutritionalmeals"}
        except:
            return redirect("/")
        return render(request, 'finance/nutritional_meals_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = user.nutritionalmeals_set.all().order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'type': obj.get_type_display(),
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'total_amount': obj.total_amount,
             'source': obj.source,
             "url": f"<a href='nutritional_meals_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
             if obj.state == 'draft' else (f"<a href='nutritional_meals_detail_view?id={obj.id}'>查看</a> | <a href='nutritional_meals_detail_view?revise=true&id={obj.id}'>修改</a>"
                                           if obj.can_revise == '1' and obj.state in ['one', 'two', 'three', 'four']
                                           else (f"<a href='nutritional_meals_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                                                 if obj.state == 'stop' else f"<a href='nutritional_meals_detail_view?id={obj.id}'>查看</a>")),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NutritionalMealsIndexView(View):
    def get(self, request):
        try:
            leaders_list = User.objects.filter(group__id=2)
            company_list = [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]
            context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name, 'uuid': uuid.uuid1(),
                       "leaders_list": leaders_list, "company_list": company_list}
        except:
            return redirect("/")
        return render(request, 'finance/nutritional_meals_index.html', context)

    def post(self, request):
        # user = request.user
        # id = request.POST.get('id', None)
        # type = request.POST.get('type', None)
        # total_amount = request.POST.get('total_amount', None)
        # source = request.POST.get('source', None)
        # payee = request.POST.get('payee', None)
        # account = request.POST.get('account', None)
        # daxie = request.POST.get('daxie', None)
        # detail_pay = request.POST.get('detail_pay', None)
        # fj_number = request.POST.get('uuid', None)
        # pay_reason = request.POST.get('pay_reason', None)
        # leaders_option = request.POST.get('leaders_option', None)           # 分管领导
        # DemandDepartment = request.POST.get('DemandDepartment', None)        # 需求科室
        # revise = request.POST.get('revise', None)                           # 是否是申请人修改
        # # ************************************************ 保存操作记录 ************************************
        # try:
        #     RecordAndPush().OperationRecords(request, "餐补付款")
        # except:
        #     pass
        # state = 'one'
        # cwk_obj = Company.objects.get(id=23)
        # rsk_obj = Company.objects.get(id=16)
        # if type == 'one' and not DemandDepartment:
        #     returnDict = {'code': 400, 'message': '请选择需求科室'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # try:
        #     gh_obj = Staffing.objects.get(station='工会主席').post_personnel.all().first()
        # except Exception as e:
        #     returnDict = {'code': 500, 'message': '工会主席岗位未维护，请联系管理员维护'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # try:
        #     yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
        # except Exception as e:
        #     returnDict = {'code': 500, 'message': '院长岗位未维护，请联系管理员维护'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # try:
        #     sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
        # except Exception as e:
        #     returnDict = {'code': 500, 'message': '书记岗位未维护，请联系管理员维护'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # try:
        #     cwzf_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        # except Exception as e:
        #     returnDict = {'code': 500, 'message': '财务支付岗位未维护，请联系管理员维护'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # if id:
        #     obj = NutritionalMeals.objects.get(id=id)
        #     obj.type = type
        #     obj.total_amount = total_amount
        #     obj.source = source
        #     obj.payee = payee
        #     obj.title = pay_reason
        #     obj.state = state
        #     obj.account = account
        #     obj.daxie = daxie
        #     obj.DemandDepartment = DemandDepartment
        #     obj.detail_pay = json.dumps(detail_pay)
        #     obj.save()
        #     if revise:
        #         obj.current_audit_users.clear()
        #         obj.nutritionalmealsauditrecord_set.all().delete()
        # else:
        #     obj = NutritionalMeals.objects.create(apply_user=request.user, company=request.user.company, state=state, title=pay_reason,
        #                                           type=type, total_amount=total_amount, source=source, detail_pay = json.dumps(detail_pay),
        #                                           fj_number=fj_number, payee=payee, account=account, daxie = daxie, DemandDepartment=DemandDepartment)
        #
        # three_appave = cwk_obj.head_people
        # if type == 'two':
        #     company_director = user.company.head_people
        #     flag = True
        #     if user != company_director:
        #         NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=company_director, audit_note='', state='unaudit', node='one')
        #         obj.current_audit_users.add(company_director)
        #         obj.state='one'
        #         flag = False
        #     # 人事科审核
        #     two_appave = rsk_obj.head_people
        #     NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=two_appave, audit_note='', state='unaudit', node='two')
        #     if flag:
        #         obj.current_audit_users.add(two_appave)
        #         obj.state = 'two'
        #     # 财务科审核
        #     NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=three_appave, audit_note='', state='unaudit', node='three')
        #     # 申请人分管领导
        #     four_appave = user.company.leaders_id
        #     NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=four_appave, audit_note='', state='unaudit', node='four')
        # else:
        #     offices_id = re.findall('\((.*?)\)', DemandDepartment)[0]
        #     offices = Company.objects.get(id=int(offices_id))
        #     need_offices = offices.head_people
        #     flag = True
        #     if user != need_offices:
        #         NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=need_offices, audit_note='', state='unaudit', node='one')
        #         obj.current_audit_users.add(need_offices)
        #         obj.state = 'one'
        #         flag = False
        #     # 财务科审核
        #     NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=three_appave, audit_note='', state='unaudit', node='three')
        #     if flag:
        #         obj.current_audit_users.add(three_appave)
        #         obj.state = 'three'
        #     # 选择的分管领导
        #     four_appave = User.objects.get(id=int(leaders_option))
        #     NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=four_appave, audit_note='', state='unaudit', node='four')
        #
        # total_amount = float(total_amount.replace(",", ""))
        # five_appave = gh_obj if total_amount <= 10000 else yz_obj if 10000 < total_amount < 200000 else sj_obj
        # NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=five_appave, audit_note='', state='unaudit', node='five')
        # NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')
        # obj.save()
        # # ********************************************** 发送小程序推送 ******************************************
        # topic_type = "餐补付款"
        # applicant = obj.apply_user.real_name
        # ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        # SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        # for jj in obj.current_audit_users.all():
        #     try:
        #         RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        #     except:
        #         pass
        # returnDict = {'code': 200, 'message': '创建成功'}
        returnDict = {'code': 200, 'message': '该流程已关闭，现已无法申请！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NutritionalMealsDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = NutritionalMeals.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        leaders_list = User.objects.filter(group__id=2)
        company_list = [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]
        context = {'realname': request.user.real_name, 'position': request.user.post, 'company_list': company_list, "leaders_list": leaders_list,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list, 'detail_pay': json.loads(json.loads(obj.detail_pay))}
        return render(request, 'finance/nutritional_meals_draft.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        type = request.POST.get('type', None)
        total_amount = request.POST.get('total_amount', 0)
        source = request.POST.get('source', None)
        payee = request.POST.get('payee', None)
        account = request.POST.get('account', None)
        daxie = request.POST.get('daxie', None) if request.POST.get('daxie', None) else ""
        detail_pay = request.POST.get('detail_pay', None)
        fj_number = request.POST.get('uuid', None)
        pay_reason = request.POST.get('pay_reason', None)
        DemandDepartment = request.POST.get('DemandDepartment', '')
        state = 'draft'
        if id:
            obj = NutritionalMeals.objects.get(id=id)
            obj.type = type
            obj.title = pay_reason
            obj.total_amount = total_amount
            obj.source = source
            obj.payee = payee
            obj.state = state
            obj.account = account
            obj.daxie = daxie
            obj.DemandDepartment = DemandDepartment
            obj.detail_pay = json.dumps(detail_pay)
            obj.save()
        else:
            obj = NutritionalMeals.objects.create(apply_user=request.user, company=request.user.company, state=state,
                                                  type=type, total_amount=total_amount, source=source, title=pay_reason,
                                                  detail_pay=json.dumps(detail_pay),
                                                  fj_number=fj_number, payee=payee, account=account, daxie=daxie, DemandDepartment=DemandDepartment)

        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NutritionalMealsDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = NutritionalMeals.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.nutritionalmealsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.nutritionalmealsauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        company_list = [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]
        leaders_list = User.objects.filter(group__id=2)
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['eight'] and request.user == obj.apply_user) or revise else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false',
                   "detail_pay": json.loads(json.loads(obj.detail_pay)),
                   "company_list": company_list, "leaders_list": leaders_list, 'revise': revise,
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                   "flow_dict": flow_dict
                   }
        return render(request, 'finance/nutritional_meals_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "餐补付款")
        except:
            pass
        obj = NutritionalMeals.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.nutritionalmealsauditrecord_set.filter(node='two'):
                    next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                else:
                    next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'three':
            audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.nutritionalmealsauditrecord_set.filter(node='four'):
                    next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                else:
                    next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='five', state='unaudit').first()
                    obj_state = 'five'
            else:
                obj_state = 'eight'
        elif obj.state == 'four':
            audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
            else:
                obj_state = 'eight'
        elif obj.state == 'five':
            audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='six', state='unaudit').first()
                obj_state = 'six'
            else:
                obj_state = 'eight'
        elif obj.state == 'six':
            audit_obj = obj.nutritionalmealsauditrecord_set.filter(node='six', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.can_revise = '0'
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "餐补付款"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NutritionalMealsRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = NutritionalMeals.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的付款申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.nutritionalmealsauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的付款申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的付款申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class NutritionalMealsWriteView(View):
    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        type = request.POST.get('type', None)
        total_amount = request.POST.get('total_amount', None)
        source = request.POST.get('source', None)
        payee = request.POST.get('payee', None)
        account = request.POST.get('account', None)
        daxie = request.POST.get('daxie', None)
        detail_pay = request.POST.get('detail_pay', None)
        fj_number = request.POST.get('uuid', None)
        pay_reason = request.POST.get('pay_reason', None)
        leaders_option = request.POST.get('leaders_option', None)  # 分管领导
        DemandDepartment = request.POST.get('DemandDepartment', None)  # 需求科室
        xiugai = request.POST.get('xiugai', None)  # 是否是管理员修改

        state = 'one'
        cwk_obj = Company.objects.get(id=23)
        rsk_obj = Company.objects.get(id=16)
        yyk_obj = Company.objects.get(id=30)
        try:
            yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
        except Exception as e:
            returnDict = {'code': 500, 'message': '院长岗位未维护，请联系管理员维护'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        try:
            sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
        except Exception as e:
            returnDict = {'code': 500, 'message': '书记岗位未维护，请联系管理员维护'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        try:
            cwzf_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        except Exception as e:
            returnDict = {'code': 500, 'message': '财务支付岗位未维护，请联系管理员维护'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj = NutritionalMeals.objects.get(id=id)
        obj.type = type
        obj.total_amount = total_amount
        obj.source = source
        obj.payee = payee
        obj.title = pay_reason
        obj.state = state
        obj.account = account
        obj.daxie = daxie
        obj.detail_pay = json.dumps(detail_pay)
        obj.DemandDepartment = DemandDepartment
        obj.save()
        if not xiugai:
            obj.current_audit_users.clear()
            obj.nutritionalmealsauditrecord_set.filter(state='unaudit', node__in=['one', 'two', 'three', 'four', 'five', 'six']).delete()
            three_appave = cwk_obj.head_people
            if type == 'two':
                company_director = user.company.head_people
                flag = True
                if user != company_director:
                    NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=company_director, audit_note='', state='unaudit', node='one')
                    obj.current_audit_users.add(company_director)
                    obj.state = 'one'
                    flag = False
                # 人事科审核
                two_appave = rsk_obj.head_people
                NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=two_appave, audit_note='', state='unaudit', node='two')
                if flag:
                    obj.current_audit_users.add(two_appave)
                    obj.state = 'two'
                # 财务科审核
                NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=three_appave, audit_note='', state='unaudit', node='three')
                # 申请人分管领导
                four_appave = user.company.leaders_id
                NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=four_appave, audit_note='', state='unaudit', node='four')
            else:
                offices_id = re.findall('\((.*?)\)', DemandDepartment)[0]
                offices = Company.objects.get(id=int(offices_id))
                need_offices = offices.head_people
                flag = True
                if user != need_offices:
                    NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=need_offices, audit_note='', state='unaudit', node='one')
                    obj.current_audit_users.add(need_offices)
                    obj.state = 'one'
                    flag = False
                # 财务科审核
                NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=three_appave, audit_note='', state='unaudit', node='three')
                if flag:
                    obj.current_audit_users.add(three_appave)
                    obj.state = 'three'
                # 选择的分管领导
                four_appave = User.objects.get(id=int(leaders_option))
                NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=four_appave, audit_note='', state='unaudit', node='four')

            total_amount = float(total_amount.replace(",", ""))
            five_appave = Company.objects.get(id=23).leaders_id if total_amount <= 10000 else yz_obj if 10000 < total_amount < 200000 else sj_obj
            NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=five_appave, audit_note='', state='unaudit', node='five')
            NutritionalMealsAuditRecord.objects.create(parent_id=obj, audit_people=cwzf_obj, audit_note='', state='unaudit', node='six')
            obj.save()
        returnDict = {'code': 200, 'message': '修改成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NewMedicalServicesListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'table_name': 'finance_newmedicalservices'}
        return render(request, 'finance/new_medical_services_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = user.newmedicalservices_set.all().order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'number': obj.number,
             'title': obj.title,
             "url": f"<a href='new_medical_services_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
             if obj.state == 'draft' else f"<a href='new_medical_services_detail_view?id={obj.id}'>查看</a> | <a href='new_medical_services_detail_view?revise=true&id={obj.id}'>修改</a>"
             if obj.can_revise == '1' and obj.state != "stop" else (
                 f"<a href='new_medical_services_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                 if obj.state == 'stop' else f"<a href='new_medical_services_detail_view?id={obj.id}'>查看</a>"),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NewMedicalServicesIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'uuid': uuid.uuid1()}
        return render(request, 'finance/new_medical_services_index.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        type = request.POST.get('type', None)
        title = request.POST.get('title', None)
        number = request.POST.get('number', None)
        reason = request.POST.get('reason', None)
        connotation = request.POST.get('connotation', None)
        note = request.POST.get('note', None)
        category = request.POST.get('category', None)
        fj_number = request.POST.get('uuid', None)
        revise = request.POST.get('revise', None)  # 是否是自己修改
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "新增医疗服务")
        except:
            pass

        if request.user.group.id not in [4, 5, 7]:
            returnDict = {'code': 400, 'message': '非临床医技科室负责人与护士长无法申请该流程！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        ywk = Company.objects.get(id=13)
        hlb = Company.objects.get(id=15)
        sjk = Company.objects.get(id=22)
        if id:
            obj = NewMedicalServices.objects.get(id=id)
            obj.type = type
            obj.title = title
            obj.can_revise='1'
            obj.number = number
            obj.reason = reason
            obj.connotation = connotation
            obj.note = note
            obj.category = category
        else:
            obj = NewMedicalServices.objects.create(apply_user=request.user, company=request.user.company, type=type, title=title, number=number, note=note, category=category,
                                                    fj_number=fj_number, reason=reason, connotation=connotation, can_revise='1')

        if revise:
            obj.newmedicalservicesauditrecord_set.all().delete()

        flag = True
        if request.user != request.user.company.head_people:
            NewMedicalServicesAuditRecord.objects.create(parent_id=obj, audit_people=request.user.company.head_people, audit_note='', state='unaudit', node='zero')
            obj.state = 'zero'
            obj.current_audit_users.add(request.user.company.head_people)
            flag = False

        if request.user.company.head_people.group.id == 4:
            one_appave = ywk.head_people
        if request.user.company.head_people.group.id == 5:
            one_appave = hlb.head_people
        NewMedicalServicesAuditRecord.objects.create(parent_id=obj, audit_people=one_appave, audit_note='', state='unaudit', node='one')
        if flag:
            obj.current_audit_users.add(one_appave)
            obj.state = 'one'
        NewMedicalServicesAuditRecord.objects.create(parent_id=obj, audit_people=sjk.head_people, audit_note='', state='unaudit', node='three')
        NewMedicalServicesAuditRecord.objects.create(parent_id=obj, audit_people=request.user.company.leaders_id, audit_note='', state='unaudit', node='four')
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "临床管理"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '创建成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NewMedicalServicesDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = NewMedicalServices.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list}
        return render(request, 'finance/new_medical_services_draft.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        type = request.POST.get('type', None)
        title = request.POST.get('title', None)
        number = request.POST.get('number', None)
        reason = request.POST.get('reason', None)
        connotation = request.POST.get('connotation', None)
        note = request.POST.get('note', None)
        category = request.POST.get('category', None)
        fj_number = request.POST.get('uuid', None)
        state = 'draft'
        if id:
            obj = NewMedicalServices.objects.get(id=id)
            obj.type = type
            obj.title = title
            obj.number = number
            obj.reason = reason
            obj.connotation = connotation
            obj.note = note
            obj.category = category
            obj.state = state
            obj.save()
        else:
            obj = NewMedicalServices.objects.create(apply_user=request.user, company=request.user.company, state=state,
                                                    type=type, title=title, number=number, note=note, category=category,
                                                    fj_number=fj_number, reason=reason, connotation=connotation)
        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NewMedicalServicesDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = NewMedicalServices.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.newmedicalservicesauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.newmedicalservicesauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['zero', 'one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['eight'] and request.user == obj.apply_user) or revise else 'false',
                   "is_stop": "true" if obj.state in ['zero', 'one', 'two', 'three', 'four', 'five', 'eight'] and request.user == obj.apply_user else 'false',
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number)[0].pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                   "flow_dict": flow_dict, "revise": revise}
        return render(request, 'finance/new_medical_services_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "新增医疗服务")
        except:
            pass
        obj = NewMedicalServices.objects.get(id=id)
        obj.audit_users_already.add(request.user)

        next_audit_obj, audit_obj = None, None
        if obj.state == 'zero':
            audit_obj = obj.newmedicalservicesauditrecord_set.filter(node='zero', state='unaudit').first()
            if state == 'audit':
                if obj.current_audit_users.count() == 1:
                    if obj.newmedicalservicesauditrecord_set.filter(node='one', state='unaudit').count():
                        next_audit_obj = obj.newmedicalservicesauditrecord_set.filter(node='one', state='unaudit').first()
                        obj_state = 'one'
                    else:
                        next_audit_obj = obj.newmedicalservicesauditrecord_set.filter(node='three', state='unaudit').first()
                        obj_state = 'three'
                else:
                    obj.current_audit_users.remove(request.user)
                    obj_state = 'zero'
            else:
                obj_state = 'eight'
        elif obj.state == 'one':
            audit_obj = obj.newmedicalservicesauditrecord_set.filter(node="one", state='unaudit').first()
            if state == 'audit':
                if obj.current_audit_users.count() == 1:
                    next_audit_obj = obj.newmedicalservicesauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                else:
                    obj.current_audit_users.remove(request.user)
                    obj_state = 'one'
            else:
                obj_state = 'eight'

        elif obj.state == 'three':
            audit_obj = obj.newmedicalservicesauditrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.newmedicalservicesauditrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'eight'

        elif obj.state == 'four':
            audit_obj = obj.newmedicalservicesauditrecord_set.filter(node='four', state='unaudit',  audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
                obj.current_audit_users.clear()
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.clear()
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.clear()
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.can_revise = '0'
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "临床管理"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class NewMedicalServicesRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = NewMedicalServices.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的付款申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.newmedicalservicesauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的付款申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的付款申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class NewMedicalServicesWriteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        type = request.POST.get('type', None)
        title = request.POST.get('title', None)
        number = request.POST.get('number', None)
        reason = request.POST.get('reason', None)
        connotation = request.POST.get('connotation', None)
        note = request.POST.get('note', None)
        category = request.POST.get('category', None)
        xiugai = request.POST.get('xiugai', None)           # 是否是管理员修改

        obj = NewMedicalServices.objects.get(id=int(id))
        if obj.state != 'eight' and not xiugai:
            returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.type = type
        obj.title = title
        obj.number = number
        obj.reason = reason
        obj.connotation = connotation
        obj.note = note
        obj.category = category
        obj.state = 'one'
        obj.save()
        if not xiugai:
            obj.current_audit_users.clear()
            if obj.newmedicalservicesauditrecord_set.filter(node='one', state='unaudit').count() == 0:
                audit_record_obj = obj.newmedicalservicesauditrecord_set.filter(node='one').first()
                NewMedicalServicesAuditRecord.objects.create(node='one', state='unaudit', audit_people=audit_record_obj.audit_people,
                                                           parent_id=obj)

            if obj.newmedicalservicesauditrecord_set.filter(node='three', state='unaudit').count() == 0:
                audit_record_obj = obj.newmedicalservicesauditrecord_set.filter(node='three').first()
                NewMedicalServicesAuditRecord.objects.create(node='three', state='unaudit', audit_people=audit_record_obj.audit_people,
                                                           parent_id=obj)

            if obj.newmedicalservicesauditrecord_set.filter(node='four', state='unaudit').count() == 0:
                audit_record_obj = obj.newmedicalservicesauditrecord_set.filter(node='four').first()
                NewMedicalServicesAuditRecord.objects.create(node='four', state='unaudit', audit_people=audit_record_obj.audit_people,
                                                           parent_id=obj)

            audit_record_obj = obj.newmedicalservicesauditrecord_set.filter(node='one').last()
            obj.current_audit_users.add(audit_record_obj.audit_people)
        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class SurgicalGradingListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, "table_name": "finance_surgicalgrading"}
        return render(request, 'finance/surgical_grading_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = user.surgicalgrading_set.all().order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'current_surgical_level': obj.current_surgical_level,
             'apply_surgical_level': obj.apply_surgical_level,
             "url": f"<a href='surgical_grading_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
             if obj.state == 'draft' else f"<a href='surgical_grading_detail_view?id={obj.id}'>查看</a> | <a href='surgical_grading_detail_view?revise=true&id={obj.id}'>修改</a>"
             if obj.can_revise == '1' and obj.state != "stop" else (
                 f"<a href='surgical_grading_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                 if obj.state == 'stop' else f"<a href='surgical_grading_detail_view?id={obj.id}'>查看</a>"),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SurgicalGradingIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'uuid': uuid.uuid1()}
        return render(request, 'finance/surgical_grading_index.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        education = request.POST.get('education', None)
        gender = request.POST.get('gender', None)
        birthday_date = request.POST.get('birthday_date', '')
        professional_title = request.POST.get('professional_title', None)
        professional_date = request.POST.get('professional_date', '')
        fixed_business = request.POST.get('fixed_business', '')
        current_surgical_level = request.POST.get('current_surgical_level', None)
        apply_surgical_level = request.POST.get('apply_surgical_level', None)
        reason = request.POST.get('reason', None)
        fj_number = request.POST.get('uuid', None)
        revise = request.POST.get('revise', None)           # 是否可以修改
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "手术分级授权")
        except:
            pass
        state = 'one'
        ywk = Company.objects.get(id=13)
        try:
            yyh_obj = Staffing.objects.get(station='医疗技术临床应用管理委员会').post_personnel.all().first()
        except Exception as e:
            returnDict = {'code': 500, 'message': '医疗技术临床应用管理委员会负责人岗位未维护，请联系管理员维护'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if id:
            obj = SurgicalGrading.objects.get(id=id)
            obj.education = education
            obj.gender = gender
            obj.birthday_date = birthday_date
            obj.professional_title = professional_title
            obj.professional_date = professional_date
            obj.fixed_business = fixed_business
            obj.current_surgical_level = current_surgical_level
            obj.apply_surgical_level = apply_surgical_level
            obj.reason = reason
            obj.save()
        else:
            obj = SurgicalGrading.objects.create(apply_user=request.user, company=request.user.company,
                                                 fj_number=fj_number,
                                                 education=education, gender=gender, birthday_date=birthday_date,
                                                 professional_title=professional_title,
                                                 professional_date=professional_date,
                                                 fixed_business=fixed_business,
                                                 current_surgical_level=current_surgical_level,
                                                 apply_surgical_level=apply_surgical_level, reason=reason)

        if not revise:
            obj.can_revise = '1'
            one_setp = request.user.company.head_people
            flag = True
            if request.user != one_setp:
                SurgicalGradingAuditRecord.objects.create(parent_id=obj, audit_people=one_setp, audit_note='', state='unaudit', node='one')
                obj.current_audit_users.add(one_setp)
                obj.state = "one"
                flag = False
            two_setp = ywk.head_people
            SurgicalGradingAuditRecord.objects.create(parent_id=obj, audit_people=two_setp, audit_note='', state='unaudit', node='two')
            if flag:
                obj.current_audit_users.add(two_setp)
                obj.state = "two"
            SurgicalGradingAuditRecord.objects.create(parent_id=obj, audit_people=yyh_obj, audit_note='', state='unaudit', node='three')
            obj.save()
            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "临床管理"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
        returnDict = {'code': 200, 'message': '创建成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SurgicalGradingDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = SurgicalGrading.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list}
        return render(request, 'finance/surgical_grading_draft.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        education = request.POST.get('education', None)
        gender = request.POST.get('gender', None)
        birthday_date = request.POST.get('birthday_date', '')
        professional_title = request.POST.get('professional_title', None)
        professional_date = request.POST.get('professional_date', '')
        fixed_business = request.POST.get('fixed_business', "")
        current_surgical_level = request.POST.get('current_surgical_level', None)
        apply_surgical_level = request.POST.get('apply_surgical_level', None)
        reason = request.POST.get('reason', None)
        fj_number = request.POST.get('uuid', None)
        state = 'draft'
        if id:
            obj = SurgicalGrading.objects.get(id=id)
            obj.education = education
            obj.gender = gender
            obj.birthday_date = birthday_date
            obj.professional_date = professional_date
            obj.professional_title = professional_title
            obj.fixed_business = fixed_business
            obj.current_surgical_level = current_surgical_level
            obj.apply_surgical_level = apply_surgical_level
            obj.reason = reason
            obj.state = state
            obj.save()
        else:
            obj = SurgicalGrading.objects.create(apply_user=request.user, company=request.user.company, state=state,
                                                 fj_number=fj_number,
                                                 education=education, gender=gender, birthday_date=birthday_date,
                                                 professional_title=professional_title,
                                                 professional_date=professional_date,
                                                 fixed_business=fixed_business,
                                                 current_surgical_level=current_surgical_level,
                                                 apply_surgical_level=apply_surgical_level, reason=reason)
        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SurgicalGradingDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = SurgicalGrading.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.surgicalgradingauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.surgicalgradingauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['eight'] and request.user == obj.apply_user) or revise else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'eight'] and request.user == obj.apply_user else 'false',
                   "flow_dict": flow_dict, "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/surgical_grading_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "手术分级授权")
        except:
            pass
        obj = SurgicalGrading.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.surgicalgradingauditrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.surgicalgradingauditrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.surgicalgradingauditrecord_set.filter(node='two', state='unaudit',
                                                                  audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.surgicalgradingauditrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'three':
            audit_obj = obj.surgicalgradingauditrecord_set.filter(node='three', state='unaudit',
                                                                  audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.can_revise = '0'
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "临床管理"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SurgicalGradingRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = SurgicalGrading.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的付款申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.surgicalgradingauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的付款申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的付款申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class SurgicalGradingWriteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        education = request.POST.get('education', None)
        gender = request.POST.get('gender', None)
        birthday_date = request.POST.get('birthday_date', None)
        professional_title = request.POST.get('professional_title', None)
        professional_date = request.POST.get('professional_date', None)
        fixed_business = request.POST.get('fixed_business', None)
        current_surgical_level = request.POST.get('current_surgical_level', None)
        apply_surgical_level = request.POST.get('apply_surgical_level', None)
        reason = request.POST.get('reason', None)
        xiugai = request.POST.get('xiugai', None)
        birthday_date = datetime.strptime(birthday_date, '%Y-%m-%d')
        professional_date = datetime.strptime(professional_date, '%Y-%m-%d')
        obj = SurgicalGrading.objects.get(id=int(id))
        if obj.state != 'eight' and not xiugai:
            returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        obj.education = education
        obj.gender = gender
        obj.birthday_date = birthday_date
        obj.professional_title = professional_title
        obj.professional_date = professional_date
        obj.fixed_business = fixed_business
        obj.current_surgical_level = current_surgical_level
        obj.apply_surgical_level = apply_surgical_level
        obj.reason = reason
        obj.save()
        if not xiugai:
            obj.current_audit_users.clear()
            flag = True
            if obj.surgicalgradingauditrecord_set.filter(node='one') and obj.surgicalgradingauditrecord_set.filter(node='one', state='unaudit').count() == 0:
                audit_record_obj = obj.surgicalgradingauditrecord_set.filter(node='one').first()
                SurgicalGradingAuditRecord.objects.create(node='one', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)
                obj.current_audit_users.add(audit_record_obj.audit_people)
                obj.state = 'one'
            if obj.surgicalgradingauditrecord_set.filter(node='two', state='unaudit').count() == 0:
                audit_record_obj = obj.surgicalgradingauditrecord_set.filter(node='two').first()
                SurgicalGradingAuditRecord.objects.create(node='two', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)
                if flag:
                    obj.current_audit_users.add(audit_record_obj.audit_people)
                    obj.state = 'two'
            if obj.surgicalgradingauditrecord_set.filter(node='three', state='unaudit').count() == 0:
                audit_record_obj = obj.surgicalgradingauditrecord_set.filter(node='three').first()
                SurgicalGradingAuditRecord.objects.create(node='three', state='unaudit', audit_people=audit_record_obj.audit_people, parent_id=obj)
            obj.save()
        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class SoloPracticeApplyListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'table_name': "finance_solopracticeapply"}
        return render(request, 'finance/solo_practice_apply_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = user.solopracticeapply_set.all().order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'university': obj.university,
             'subject': obj.subject,
             "url": f"<a href='solo_practice_apply_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
             if obj.state == 'draft' else f"<a href='solo_practice_apply_detail_view?id={obj.id}'>查看</a> | <a href='solo_practice_apply_detail_view?revise=true&id={obj.id}'>修改</a>"
             if obj.can_revise == '1' and obj.state != 'stop' else (f"<a href='solo_practice_apply_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                                                                    if obj.state == 'stop' else f"<a href='solo_practice_apply_detail_view?id={obj.id}'>查看</a>"),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SoloPracticeApplyIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'uuid': uuid.uuid1(),
                   'signature_picture': '/media' + '/' + str(request.user.signature_picture) if request.user.signature_picture else ''}
        return render(request, 'finance/solo_practice_apply_index.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        university = request.POST.get('university', None)
        subject = request.POST.get('subject', None)
        birthday_date = request.POST.get('birthday_date', None)
        doctor_qualified_number = request.POST.get('doctor_qualified_number', None)
        doctor_qualified_date = request.POST.get('doctor_qualified_date', None)
        doctor_ractice_number = request.POST.get('doctor_ractice_number', None)
        doctor_ractice_date = request.POST.get('doctor_ractice_date', None)
        revise = request.POST.get('revise', '')
        fj_number = request.POST.get('uuid', None)
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "临床医师单独执业资格")
        except:
            pass
        birthday_date = datetime.strptime(birthday_date, '%Y-%m-%d')
        doctor_qualified_date = datetime.strptime(doctor_qualified_date, '%Y-%m-%d')
        doctor_ractice_date = datetime.strptime(doctor_ractice_date, '%Y-%m-%d')
        ywk = Company.objects.get(id=13)
        if id:
            obj = SoloPracticeApply.objects.get(id=id)
            obj.university = university
            obj.subject = subject
            obj.birthday_date = birthday_date
            obj.doctor_qualified_number = doctor_qualified_number
            obj.doctor_qualified_date = doctor_qualified_date
            obj.doctor_ractice_number = doctor_ractice_number
            obj.doctor_ractice_date = doctor_ractice_date
            obj.save()
        else:
            obj = SoloPracticeApply.objects.create(apply_user=request.user, company=request.user.company,
                                                   fj_number=fj_number, signature_picture=request.user.signature_picture,
                                                   university=university, subject=subject, birthday_date=birthday_date,
                                                   doctor_qualified_number=doctor_qualified_number, doctor_qualified_date=doctor_qualified_date,
                                                   doctor_ractice_number=doctor_ractice_number, doctor_ractice_date=doctor_ractice_date)

        if not revise:
            obj.can_revise = '1'
            one_setp = request.user.company.head_people
            flag = True
            if request.user != one_setp:
                SoloPracticeApplyAuditRecord.objects.create(parent_id=obj, audit_people=one_setp, audit_note='', state='unaudit', node='one')
                obj.current_audit_users.add(one_setp)
                obj.state = "one"
                flag = False
            two_step = ywk.head_people
            SoloPracticeApplyAuditRecord.objects.create(parent_id=obj, audit_people=two_step, audit_note='', state='unaudit', node='two')
            if flag:
                obj.current_audit_users.add(two_step)
                obj.state = "two"
            obj.save()
            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "临床管理"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = "临床医师单独执业资格申请"
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
        returnDict = {'code': 200, 'message': '创建成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SoloPracticeApplyDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = SoloPracticeApply.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list}
        return render(request, 'finance/solo_practice_apply_draft.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        university = request.POST.get('university', None)
        subject = request.POST.get('subject', None)
        birthday_date = request.POST.get('birthday_date', None)
        doctor_qualified_number = request.POST.get('doctor_qualified_number', None)
        doctor_qualified_date = request.POST.get('doctor_qualified_date', None)
        doctor_ractice_number = request.POST.get('doctor_ractice_number', None)
        doctor_ractice_date = request.POST.get('doctor_ractice_date', None)
        fj_number = request.POST.get('uuid', None)
        birthday_date = datetime.strptime(birthday_date, '%Y-%m-%d')
        doctor_qualified_date = datetime.strptime(doctor_qualified_date, '%Y-%m-%d')
        doctor_ractice_date = datetime.strptime(doctor_ractice_date, '%Y-%m-%d')
        state = 'draft'
        if id:
            obj = SoloPracticeApply.objects.get(id=id)
            obj.university = university
            obj.subject = subject
            obj.birthday_date = birthday_date
            obj.doctor_qualified_number = doctor_qualified_number
            obj.doctor_qualified_date = doctor_qualified_date
            obj.doctor_ractice_number = doctor_ractice_number
            obj.doctor_ractice_date = doctor_ractice_date
            obj.state = state
            obj.save()
        else:
            obj = SoloPracticeApply.objects.create(apply_user=request.user, company=request.user.company, state=state,
                                                   fj_number=fj_number,
                                                   signature_picture=request.user.signature_picture,
                                                   university=university, subject=subject, birthday_date=birthday_date,
                                                   doctor_qualified_number=doctor_qualified_number,
                                                   doctor_qualified_date=doctor_qualified_date,
                                                   doctor_ractice_number=doctor_ractice_number,
                                                   doctor_ractice_date=doctor_ractice_date)
        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SoloPracticeApplyDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', "")
        obj = SoloPracticeApply.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.solopracticeapplyauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.solopracticeapplyauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (obj.state in ['eight'] and request.user == obj.apply_user) or revise else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'eight'] and request.user == obj.apply_user else 'false',
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number)[0].pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "",
                   "flow_dict": flow_dict, "revise": revise
                   }
        return render(request, 'finance/solo_practice_apply_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "临床医师单独执业资格")
        except:
            pass
        obj = SoloPracticeApply.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.solopracticeapplyauditrecord_set.filter(node='one', state='unaudit',
                                                                    audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.solopracticeapplyauditrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.solopracticeapplyauditrecord_set.filter(node='two', state='unaudit',
                                                                    audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'

        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.can_revise = '0'
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "临床管理"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = "临床医师单独执业资格申请"
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SoloPracticeApplyRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = SoloPracticeApply.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的付款申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.solopracticeapplyauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的付款申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的付款申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class SoloPracticeApplyWriteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        university = request.POST.get('university', None)
        subject = request.POST.get('subject', None)
        birthday_date = request.POST.get('birthday_date', None)
        doctor_qualified_number = request.POST.get('doctor_qualified_number', None)
        doctor_qualified_date = request.POST.get('doctor_qualified_date', None)
        doctor_ractice_number = request.POST.get('doctor_ractice_number', None)
        doctor_ractice_date = request.POST.get('doctor_ractice_date', None)
        xiugai = request.POST.get('xiugai', None)
        birthday_date = datetime.strptime(birthday_date, '%Y-%m-%d')
        doctor_qualified_date = datetime.strptime(doctor_qualified_date, '%Y-%m-%d')
        doctor_ractice_date = datetime.strptime(doctor_ractice_date, '%Y-%m-%d')
        obj = SoloPracticeApply.objects.get(id=int(id))
        if obj.state != 'eight' and not xiugai:
            returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.university = university
        obj.subject = subject
        obj.birthday_date = birthday_date
        obj.doctor_qualified_number = doctor_qualified_number
        obj.doctor_qualified_date = doctor_qualified_date
        obj.doctor_ractice_number = doctor_ractice_number
        obj.doctor_ractice_date = doctor_ractice_date
        obj.save()

        if not xiugai:
            obj.current_audit_users.clear()
            ywk = Company.objects.get(id=13)
            obj.solopracticeapplyauditrecord_set.filter(state='unaudit').delete()
            one_setp = request.user.company.head_people
            flag = True
            if request.user != one_setp:
                SoloPracticeApplyAuditRecord.objects.create(parent_id=obj, audit_people=one_setp, audit_note='', state='unaudit', node='one')
                obj.current_audit_users.add(one_setp)
                obj.state = "one"
                flag = False
            two_step = ywk.head_people
            SoloPracticeApplyAuditRecord.objects.create(parent_id=obj, audit_people=two_step, audit_note='', state='unaudit', node='two')
            if flag:
                obj.current_audit_users.add(two_step)
                obj.state = "two"
            obj.save()

        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class BusinessContractListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name}
        return render(request, 'finance/business_contract_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = user.businesscontract_set.all().order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'contract_name': obj.contract_name,
             'contract_number': obj.contract_number,
             "url": f"<a href='business_contract_draft_view?id={obj.id}'>编辑</a>"
             if obj.state == 'draft' else (f"<a href='business_contract_detail_view?id={obj.id}'>查看</a>"
                 if obj.state == 'stop' else f"<a href='business_contract_detail_view?id={obj.id}'>查看</a>"),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class BusinessContractIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'uuid': uuid.uuid1(),
                   'date': datetime.now().strftime("%Y-%m-%d %H:%M"), #"conf_obj": conf_dict,
                   'company_list': [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]
                   }
        return render(request, 'finance/business_contract_index.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        product_company_id = request.POST.get('product_company_id', None)
        contract_name = request.POST.get('contract_name', None)
        contract_number = request.POST.get('contract_number', None)
        documentation = request.POST.get('documentation', None)
        other_units = request.POST.get('other_units', None)
        contract_amount = request.POST.get('contract_amount', None)
        source = request.POST.get('source', None)
        contract_type = request.POST.get('contract_type', None)
        content = request.POST.get('content', None)
        fj_number = request.POST.get('uuid', None)
        Printing = request.POST.get('Printing', None)
        give_back = request.POST.get('give_back', None)             # 退回修改
        xiugai = request.POST.get('xiugai', None)
        contract_effect = request.POST.get('contract_effect', None)
        contract_off = request.POST.get('contract_off', None)
        summary_path = request.POST.get('summary_path', None)
        association_topic = request.POST.get('association_topic', None)
        summary_name = request.POST.get('summary_name', "")
        notes = request.POST.get('beizhu', "")
        product_company_id = product_company_id.split(',')
        greater = request.POST.get('greater', None)             # 金额是否大于20万
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "合同会签")
        except:
            pass
        try:
            if float(contract_amount.replace(',', '')) >= 200000:
                greater = '1'
            else:
                greater = '0'
        except:
            greater = greater

        if not contract_name:
            returnDict = {'code': 500, 'message': '合同名称不能为空'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        state = 'one'
        cwk = Company.objects.get(id=23)
        jcs = Company.objects.get(id=18)
        sjk = Company.objects.get(id=22)

        jcs_user = jcs.head_people

        if id:
            obj = BusinessContract.objects.get(id=id)
            obj.product_company_id = 87
            obj.contract_name = contract_name
            obj.contract_number = contract_number
            obj.documentation = documentation
            obj.contract_amount = contract_amount
            obj.other_units = other_units
            obj.Printing = Printing
            obj.greater = greater
            obj.contract_type = contract_type
            obj.source = source
            obj.content = content
            obj.contract_effect = contract_effect
            obj.contract_off = contract_off
            obj.state = state
            obj.notes = notes
            # obj.summary_path = summary_path
            # obj.summary_name = summary_name
            # obj.association_topic = Topics.objects.get(id=int(association_topic)) if association_topic else None
            obj.save()
            if give_back:
                obj.businesscontractauditrecord_set.filter(state="unaudit").delete()
        else:
            obj = BusinessContract.objects.create(apply_user=request.user, company=request.user.company, state=state, fj_number=fj_number, product_company_id=87, contract_name=contract_name, contract_number=contract_number,
                                                  documentation=documentation, contract_amount=contract_amount, other_units=other_units, content=content, source=source, Printing=Printing, greater=greater, contract_effect=contract_effect,
                                                  contract_off=contract_off, contract_type=contract_type, notes=notes)

        for com in product_company_id:
            obj.requirement_department.add(Company.objects.get(id=int(com.strip())))

        if not xiugai:
            obj.current_audit_users.clear()

            one_audit = obj.company.head_people
            flag = True
            if user != one_audit:
                BusinessContractAuditRecord.objects.create(parent_id=obj, audit_people=one_audit, audit_note='', state='unaudit', node='one')
                obj.current_audit_users.add(one_audit)
                obj.state='one'
                obj.save()
                flag = False

            flag1 = True
            for two_audit in obj.requirement_department.all():
                two_sept = two_audit.head_people
                if one_audit != two_sept:
                    flag1 = False
                    BusinessContractAuditRecord.objects.create(parent_id=obj, audit_people=two_sept, audit_note='', state='unaudit', node='two')
                    if flag:
                        obj.current_audit_users.add(two_sept)
                        obj.state = 'two'
                        obj.save()

            three_audit = cwk.head_people
            BusinessContractAuditRecord.objects.create(parent_id=obj, audit_people=three_audit, audit_note='', state='unaudit', node='three')
            if flag and flag1:
                obj.current_audit_users.add(three_audit)
                obj.state = 'three'
                obj.save()

            BusinessContractAuditRecord.objects.create(parent_id=obj, audit_people=jcs_user, audit_note='', state='unaudit', node='four')

            five_audit = sjk.head_people
            BusinessContractAuditRecord.objects.create(parent_id=obj, audit_people=five_audit, audit_note='', state='unaudit', node='five')

            BusinessContractAuditRecord.objects.create(parent_id=obj, audit_people=request.user.company.leaders_id, audit_note='', state='unaudit', node='six')

            if greater == '1':
                BusinessContractAuditRecord.objects.create(parent_id=obj, audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), audit_note='', state='unaudit', node='nine')
                BusinessContractAuditRecord.objects.create(parent_id=obj, audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), audit_note='', state='unaudit', node='ten')

            BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
            BusinessContractAuditRecord.objects.create(node='eleven', state='unaudit', audit_people=BGS_appave, parent_id=obj)
            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "合同会签"
            applicant = obj.apply_user.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.contract_name[:15] + "……" if len(obj.contract_name) > 15 else obj.contract_name
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
        returnDict = {'code': 200, 'message': '创建成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")
        # returnDict = {'status': 'success', 'message': "该流程已关闭，现已无法申请！", 'code': 400}
        # return HttpResponse(json.dumps(returnDict), content_type="application/json")


class BusinessContractDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = BusinessContract.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        if obj.product_company.id == 87:
            xuqiu_dep, xuqiu_id = [], []
            for tt in obj.requirement_department.all():
                xuqiu_dep.append(tt.name)
                xuqiu_id.append(str(tt.id))
        else:
            xuqiu_dep, xuqiu_id = [obj.product_company.name], [str(obj.product_company.id)]

        context = {'realname': request.user.real_name, 'position': request.user.post, "xuqiu_dep_str": ", ".join(xuqiu_dep), "xuqiu_id_str": ", ".join(xuqiu_id),
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   'company_list': [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]}
        return render(request, 'finance/business_contract_draft.html', context)

    def post(self, request):
        # user = request.user
        # id = request.POST.get('id', "")
        # product_company_id = request.POST.get('product_company_id', "")
        # contract_name = request.POST.get('contract_name', "")
        # contract_number = request.POST.get('contract_number', "")
        # documentation = request.POST.get('documentation', "")
        # other_units = request.POST.get('other_units', "")
        # contract_amount = request.POST.get('contract_amount', "")
        # source = request.POST.get('source', "")
        # contract_type = request.POST.get('contract_type', "")
        # content = request.POST.get('content', "")
        # fj_number = request.POST.get('uuid', "")
        # Printing = request.POST.get('Printing', "")
        # contract_effect = request.POST.get('contract_effect', "")
        # contract_off = request.POST.get('contract_off', "")
        # summary_path = request.POST.get('summary_path', "")
        # association_topic = request.POST.get('association_topic', "")
        # summary_name = request.POST.get('summary_name', "")
        # notes = request.POST.get('beizhu', "")
        # state = 'draft'
        # product_company_id = product_company_id.split(',')
        # if id:
        #     obj = BusinessContract.objects.get(id=id)
        #     obj.product_company_id = 87
        #     obj.contract_name = contract_name
        #     obj.contract_number = contract_number
        #     obj.documentation = documentation
        #     obj.contract_amount = contract_amount
        #     obj.contract_effect = contract_effect
        #     obj.contract_off = contract_off
        #     obj.other_units = other_units
        #     obj.Printing = Printing
        #     obj.source = source
        #     obj.contract_type = contract_type
        #     obj.content = content
        #     obj.state = state
        #     obj.summary_path = summary_path
        #     obj.summary_name = summary_name
        #     obj.notes = notes
        #     obj.association_topic = Topics.objects.get(id=int(association_topic)) if association_topic else None
        #     obj.save()
        # else:
        #     obj = BusinessContract.objects.create(apply_user=request.user, company=request.user.company, state=state,
        #                                           fj_number=fj_number, Printing=Printing, product_company_id=87,
        #                                           contract_name=contract_name, contract_number=contract_number, documentation=documentation, contract_amount=contract_amount,
        #                                           other_units=other_units, content=content, source=source, contract_effect=contract_effect,
        #                                           contract_off=contract_off, contract_type=contract_type, summary_path=summary_path, summary_name=summary_name,
        #                                           association_topic=Topics.objects.get(id=int(association_topic)) if association_topic else None, notes=notes)
        # for com in product_company_id:
        #     obj.requirement_department.add(Company.objects.get(id=int(com.strip())))
        # returnDict = {'code': 200, 'message': '保存成功'}
        # return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'status': 'success', 'message': "该流程已关闭，现已无法保存！", 'code': 400}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class BusinessContractDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = BusinessContract.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.businesscontractauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.businesscontractauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "file_type": atta_obj.file_type,
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        flag = 'flase'
        for t in file_list:
            if t['file_type'] == '1':
                flag = 'true'

        if obj.product_company.id == 87:
            xuqiu_dep, xuqiu_id = [], []
            for tt in obj.requirement_department.all():
                xuqiu_dep.append(tt.name)
                xuqiu_id.append(str(tt.id))
        else:
            xuqiu_dep, xuqiu_id = [obj.product_company.name], [str(obj.product_company.id)]

        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic, "flag": flag, "xuqiu_dep_str": ", ".join(xuqiu_dep), "xuqiu_id_str": ", ".join(xuqiu_id),
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'nine', 'ten', 'eleven'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if obj.state in ['eight'] and request.user == obj.apply_user else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'nine', 'ten', 'eleven'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else "", "flow_dict": flow_dict,
                   'company_list': [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]
                   }
        return render(request, 'finance/business_contract_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "合同会签")
        except:
            pass
        obj = BusinessContract.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        if obj.state != 'two':
            obj.current_audit_users.clear()

        if obj.state == 'one':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.businesscontractauditrecord_set.filter(node='two'):
                    next_audit_list = obj.businesscontractauditrecord_set.filter(node='two', state='unaudit')
                    obj_state = 'two'
                    for next_audit_obj in next_audit_list:
                        obj.current_audit_users.add(next_audit_obj.audit_people)
                else:
                    next_audit_obj = obj.businesscontractauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.businesscontractauditrecord_set.filter(node='two', state='unaudit').count() == 1:
                    obj.current_audit_users.clear()
                    next_audit_obj = obj.businesscontractauditrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_obj.audit_people)
                else:
                    obj.current_audit_users.remove(request.user)
                    obj_state = 'two'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.businesscontractauditrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.businesscontractauditrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.businesscontractauditrecord_set.filter(node='six', state='unaudit').first()
                obj_state = 'six'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='six', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.businesscontractauditrecord_set.filter(node='nine', state='unaudit'):
                    next_audit_obj = obj.businesscontractauditrecord_set.filter(node='nine', state='unaudit').first()
                    obj_state = 'nine'
                else:
                    next_audit_obj = obj.businesscontractauditrecord_set.filter(node='eleven', state='unaudit').first()
                    obj_state = 'eleven'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'nine':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='nine', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.businesscontractauditrecord_set.filter(node='ten', state='unaudit').first()
                obj_state = 'ten'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'ten':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='ten', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.businesscontractauditrecord_set.filter(node='eleven', state='unaudit').first()
                obj_state = 'eleven'
                obj.current_audit_users.add(next_audit_obj.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'eleven':
            audit_obj = obj.businesscontractauditrecord_set.filter(node='eleven', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
                if not obj.businesscontractauditrecord_set.filter(node='ten'):
                    MakeCopy.objects.create(recipient=Staffing.objects.get(station='院长').post_personnel.all().first(), process_id=obj.id, type='f')
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "合同会签"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.contract_name[:15] + "……" if len(obj.contract_name) > 15 else obj.contract_name
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class BusinessContractRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = BusinessContract.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.businesscontractauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class BusinessContractWriteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        product_company_id = request.POST.get('product_company_id', None)
        contract_name = request.POST.get('contract_name', None)
        contract_number = request.POST.get('contract_number', None)
        documentation = request.POST.get('documentation', None)
        other_units = request.POST.get('other_units', None)
        contract_amount = request.POST.get('contract_amount', None)
        source = request.POST.get('source', None)
        content = request.POST.get('content', None)
        fj_number = request.POST.get('uuid', None)
        product_company_id = int(product_company_id)
        obj = SurgicalGrading.objects.get(id=int(id))
        if obj.state != 'eight':
            returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        try:
            yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
        except Exception as e:
            returnDict = {'code': 500, 'message': '院长岗位未维护，请联系管理员维护'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        try:
            sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
        except Exception as e:
            returnDict = {'code': 500, 'message': '书记岗位未维护，请联系管理员维护'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj = BusinessContract.objects.get(id=id)
        obj.product_company_id = product_company_id
        obj.contract_name = contract_name
        obj.contract_number = contract_number
        obj.documentation = documentation
        obj.contract_amount = contract_amount
        obj.other_units = other_units
        obj.source = source
        obj.content = content
        obj.state = 'one'
        obj.current_audit_users.clear()
        obj.save()
        if obj.businesscontractauditrecord_set.filter(node='one', state='unaudit').count() == 0:
            audit_record_obj = obj.businesscontractauditrecord_set.filter(node='one').first()

            BusinessContractAuditRecord.objects.create(node='one', state='unaudit',
                                                       audit_people=audit_record_obj.audit_people,
                                                       parent_id=obj)
        if obj.businesscontractauditrecord_set.filter(node='two', state='unaudit').count() == 0:
            audit_record_obj = obj.businesscontractauditrecord_set.filter(node='two').first()

            BusinessContractAuditRecord.objects.create(node='two', state='unaudit',
                                                       audit_people=audit_record_obj.audit_people,
                                                       parent_id=obj)
        if obj.businesscontractauditrecord_set.filter(node='three', state='unaudit').count() == 0:
            audit_record_obj = obj.businesscontractauditrecord_set.filter(node='three').first()

            BusinessContractAuditRecord.objects.create(node='three', state='unaudit',
                                                       audit_people=audit_record_obj.audit_people,
                                                       parent_id=obj)
        if obj.businesscontractauditrecord_set.filter(node='four', state='unaudit').count() == 0:
            audit_record_obj = obj.businesscontractauditrecord_set.filter(node='four').first()

            BusinessContractAuditRecord.objects.create(node='four', state='unaudit',
                                                       audit_people=audit_record_obj.audit_people,
                                                       parent_id=obj)
        if obj.businesscontractauditrecord_set.filter(node='five', state='unaudit').count() == 0:
            audit_record_obj = obj.businesscontractauditrecord_set.filter(node='five').first()

            BusinessContractAuditRecord.objects.create(node='five', state='unaudit',
                                                       audit_people=audit_record_obj.audit_people,
                                                       parent_id=obj)
        if obj.businesscontractauditrecord_set.filter(node='six', state='unaudit').count() == 0:
            audit_record_obj = obj.businesscontractauditrecord_set.filter(node='six').first()

            BusinessContractAuditRecord.objects.create(node='six', state='unaudit',
                                                       audit_people=audit_record_obj.audit_people,
                                                       parent_id=obj)
        if obj.businesscontractauditrecord_set.filter(node='seven', state='unaudit').count() == 0:
            audit_record_obj = obj.businesscontractauditrecord_set.filter(node='seven').first()

            BusinessContractAuditRecord.objects.create(node='seven', state='unaudit',
                                                       audit_people=audit_record_obj.audit_people,
                                                       parent_id=obj)
        if obj.businesscontractauditrecord_set.filter(node='eight', state='unaudit').count() == 0:
            audit_record_obj = obj.businesscontractauditrecord_set.filter(node='eight').first()

            BusinessContractAuditRecord.objects.create(node='eight', state='unaudit',
                                                       audit_people=audit_record_obj.audit_people,
                                                       parent_id=obj)
        obj.businesscontractauditrecord_set.filter(node='nine', state='unaudit').delete()
        BusinessContractAuditRecord.objects.create(parent_id=obj,
                                                   audit_people=sj_obj if obj.contract_amount >= 200000 else yz_obj,
                                                   audit_note='', state='unaudit', node='nine')
        audit_record_obj = obj.businesscontractauditrecord_set.filter(node='one').last()
        obj.current_audit_users.add(audit_record_obj.audit_people)
        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class delete_business_flow(View):
    def post(self, request):
        flow_id = request.POST.get("id", '')
        obj = BusinessContract.objects.get(id=int(flow_id))
        if obj.state not in ['draft', 'eight', 'stop']:
            returnDict = {'code': 400, 'message': '删除失败！只有草稿或退回流程可以删除。'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        MakeCopy.objects.filter(type='f', process_id=flow_id).delete()
        obj.businesscontractauditrecord_set.all().delete()
        obj.audit_users_already.clear()
        obj.current_audit_users.clear()
        obj.delete()
        print("================================", "删除成功！")
        returnDict = {'code': 200, 'message': '删除成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PayWithBloodListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name}
        return render(request, 'finance/pay_with_blood_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        objs = user.paywithblood_set.all().order_by('-create_time')
        data_list = [
            {'id': obj.id,
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'current_audit_user': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
             'title': obj.title,
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'total_amount': obj.total_amount,
             "url": "pay_with_blood_draft_view?id=" + str(
                 obj.id) if obj.state == 'draft' else "pay_with_blood_detail_view?id=" + str(obj.id),
             'state_display': obj.get_state_str()} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PayWithBloodIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'uuid': uuid.uuid1()}
        return render(request, 'finance/pay_with_blood_index.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        title = request.POST.get('title', None)
        total_amount = request.POST.get('total_amount', None)
        remarks = request.POST.get('remarks', None)
        fj_number = request.POST.get('uuid', None)
        state = 'one'
        total_amount = float(total_amount)
        cwk_obj = Company.objects.get(id=23)
        try:
            yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
        except Exception as e:
            returnDict = {'code': 500, 'message': '院长岗位未维护，请联系管理员维护'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        try:
            sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
        except Exception as e:
            returnDict = {'code': 500, 'message': '书记岗位未维护，请联系管理员维护'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        try:
            cwzf_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        except Exception as e:
            returnDict = {'code': 500, 'message': '财务支付岗位未维护，请联系管理员维护'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        try:
            clkj_obj = Staffing.objects.get(station='材料会计').post_personnel.all().first()
        except Exception as e:
            returnDict = {'code': 500, 'message': '材料会计岗位未维护，请联系管理员维护'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if id:
            obj = PayWithBlood.objects.get(id=id)
            obj.title = title
            obj.total_amount = total_amount
            obj.remarks = remarks
            obj.state = state
            obj.save()
        else:
            obj = PayWithBlood.objects.create(apply_user=request.user, company=request.user.company, state=state,
                                                title=title, total_amount=total_amount, remarks=remarks, fj_number=fj_number)
        PayWithBloodAuditRecord.objects.create(parent_id=obj,
                                               audit_people=clkj_obj.user,
                                               audit_note='', state='unaudit', node='one')
        PayWithBloodAuditRecord.objects.create(parent_id=obj,
                                               audit_people=cwk_obj.head_people,
                                               audit_note='', state='unaudit', node='two')
        PayWithBloodAuditRecord.objects.create(parent_id=obj,
                                               audit_people=user.company.leaders_id,
                                               audit_note='', state='unaudit', node='three')
        PayWithBloodAuditRecord.objects.create(parent_id=obj,
                                               audit_people=cwk_obj.leaders_id,
                                               audit_note='', state='unaudit', node='four')
        if total_amount >= 10000:
            PayWithBloodAuditRecord.objects.create(parent_id=obj,
                                                   audit_people=sj_obj if total_amount >= 200000 else yz_obj,
                                                   audit_note='', state='unaudit', node='five')
        PayWithBloodAuditRecord.objects.create(parent_id=obj,
                                               audit_people=cwzf_obj,
                                               audit_note='', state='unaudit', node='six')
        obj.current_audit_users.add(clkj_obj)
        returnDict = {'code': 200, 'message': '创建成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PayWithBloodDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = PayWithBlood.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list}
        return render(request, 'finance/pay_with_blood_draft.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        title = request.POST.get('title', None)
        total_amount = request.POST.get('total_amount', None)
        remarks = request.POST.get('remarks', None)
        fj_number = request.POST.get('uuid', None)
        state = 'draft'
        total_amount = float(total_amount)
        if id:
            obj = PayWithBlood.objects.get(id=id)
            obj.title = title
            obj.total_amount = total_amount
            obj.remarks = remarks
            obj.state = state
            obj.save()
        else:
            obj = PayWithBlood.objects.create(apply_user=request.user, company=request.user.company, state=state,
                                              title=title, total_amount=total_amount, remarks=remarks,
                                              fj_number=fj_number)
        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PayWithBloodDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect("/")
        id = request.GET.get('id', None)
        obj = PayWithBlood.objects.get(id=id)
        audit_dic = {}
        for audit_obj in obj.paywithbloodauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                   "audit_dic": audit_dic,
                   "is_audit": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if obj.state in ['eight'] and request.user == obj.apply_user else 'false',
                   "is_stop": "true" if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false',
                   }
        return render(request, 'finance/pay_with_blood_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        obj = PayWithBlood.objects.get(id=id)
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        next_audit_obj = None
        if obj.state == 'one':
            audit_obj = obj.paywithbloodauditrecord_set.filter(node='one', state='unaudit',
                                                               audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.paywithbloodauditrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
            else:
                obj_state = 'eight'
        elif obj.state == 'two':
            audit_obj = obj.paywithbloodauditrecord_set.filter(node='two', state='unaudit',
                                                               audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.paywithbloodauditrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
            else:
                obj_state = 'eight'
        elif obj.state == 'three':
            audit_obj = obj.paywithbloodauditrecord_set.filter(node='three', state='unaudit',
                                                               audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.paywithbloodauditrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
            else:
                obj_state = 'eight'
        elif obj.state == 'four':
            audit_obj = obj.paywithbloodauditrecord_set.filter(node='four', state='unaudit',
                                                               audit_people=request.user).first()
            if state == 'audit':
                if obj.total_amount >= 10000:
                    next_audit_obj = obj.paywithbloodauditrecord_set.filter(node='five', state='unaudit').first()
                    obj_state = 'five'
                else:
                    next_audit_obj = obj.paywithbloodauditrecord_set.filter(node='six', state='unaudit').first()
                    obj_state = 'six'
            else:
                obj_state = 'eight'
        elif obj.state == 'five':
            audit_obj = obj.paywithbloodauditrecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_obj = obj.paywithbloodauditrecord_set.filter(node='six', state='unaudit').first()
                obj_state = 'six'
            else:
                obj_state = 'eight'
        elif obj.state == 'six':
            audit_obj = obj.paywithbloodauditrecord_set.filter(node='six', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
        else:
            returnDict = {'code': 500, 'message': '审核错误，状态不正确'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        audit_obj.update_time = datetime.now()
        audit_obj.state = state
        audit_obj.audit_note = audit_note
        audit_obj.save()
        obj.state = obj_state
        if obj_state == 'eight':
            obj.current_audit_users.add(obj.apply_user)
        if next_audit_obj:
            obj.current_audit_users.add(next_audit_obj.audit_people)
        obj.save()
        returnDict = {'code': 200, 'message': '审核成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class PayWithBloodRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = PayWithBlood.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的付款申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.paywithbloodauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的付款申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的付款申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class PayWithBloodWriteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        title = request.POST.get('title', None)
        total_amount = request.POST.get('total_amount', None)
        remarks = request.POST.get('remarks', None)
        obj = PayWithBlood.objects.get(id=int(id))
        if obj.state != 'eight':
            returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        total_amount = float(total_amount)
        obj.title = title
        obj.total_amount = total_amount
        obj.remarks = remarks
        obj.state = 'one'
        obj.current_audit_users.clear()
        obj.save()
        cwk_obj = Company.objects.get(id=23)
        clkj_obj = Staffing.objects.get(station='材料会计').post_personnel.all().first()
        if obj.paywithbloodauditrecord_set.filter(node='one', state='unaudit').count() == 0:
            audit_record_obj = obj.paywithbloodauditrecord_set.filter(node='one').first()

            PayWithBloodAuditRecord.objects.create(node='one', state='unaudit',
                                                   audit_people=audit_record_obj.audit_people,
                                                   parent_id=obj)
        if obj.paywithbloodauditrecord_set.filter(node='two', state='unaudit').count() == 0:
            audit_record_obj = obj.paywithbloodauditrecord_set.filter(node='two').first()

            PayWithBloodAuditRecord.objects.create(node='two', state='unaudit',
                                                   audit_people=audit_record_obj.audit_people,
                                                   parent_id=obj)
        if obj.paywithbloodauditrecord_set.filter(node='three', state='unaudit').count() == 0:
            audit_record_obj = obj.paywithbloodauditrecord_set.filter(node='three').first()

            PayWithBloodAuditRecord.objects.create(node='three', state='unaudit',
                                                   audit_people=audit_record_obj.audit_people,
                                                   parent_id=obj)
        if obj.paywithbloodauditrecord_set.filter(node='four', state='unaudit').count() == 0:
            audit_record_obj = obj.paywithbloodauditrecord_set.filter(node='four').first()

            PayWithBloodAuditRecord.objects.create(node='four', state='unaudit',
                                                   audit_people=audit_record_obj.audit_people,
                                                   parent_id=obj)
        obj.paywithbloodauditrecord_set.filter(node='five', state='unaudit').delete()
        yz_obj = Staffing.objects.get(station='院长').post_personnel.all().first()
        sj_obj = Staffing.objects.get(station='书记').post_personnel.all().first()
        if total_amount >= 10000:
            PayWithBloodAuditRecord.objects.create(parent_id=obj,
                                                   audit_people=sj_obj if total_amount >= 200000 else yz_obj,
                                                   audit_note='', state='unaudit', node='five')
        if obj.paywithbloodauditrecord_set.filter(node='six', state='unaudit').count() == 0:
            audit_record_obj = obj.paywithbloodauditrecord_set.filter(node='five').first()

            PayWithBloodAuditRecord.objects.create(node='six', state='unaudit',
                                                   audit_people=audit_record_obj.audit_people,
                                                   parent_id=obj)
        audit_record_obj = obj.paywithbloodauditrecord_set.filter(node='one').last()
        obj.current_audit_users.add(audit_record_obj.audit_people)
        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


# 维修维保流程创建
class MaintainServerApplyView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "uuid": uuid.uuid1()}
        return render(request, 'finance/maintain_server_apply.html', context)

    def post(self, request):
        user = request.user
        title = request.POST.get('title', None)         # 付款标题
        total_money = request.POST.get('total_money', 0)     # 付款总金额
        id = request.POST.get('id', None)
        company = request.user.company     # 上传科室
        financial = request.POST.get('financial', '')
        fj_number = request.POST.get('fj_number', None)
        job_num = ''
        if id:
            obj = MaintainServer.objects.get(id=id)
            obj.apply_user = user
            obj.state = 'one'
            obj.title = title
            obj.total_money = total_money
            obj.company = company
            obj.financial = financial
            obj.fj_number = fj_number
            obj.save()
        else:
            obj = MaintainServer.objects.create(apply_user=user, state='one',
                                             title=title, total_money=total_money,
                                             company=company, financial=financial, fj_number=fj_number,)
        sbk_obj = Company.objects.get(id=26)
        obj.current_audit_users.add(sbk_obj.head_people)
        MaintainServerAuditRecord.objects.create(node='SBKZ', state='unaudit', audit_people=sbk_obj.head_people, parent_id=obj)
        cwk_obj = Company.objects.get(id=23)
        MaintainServerAuditRecord.objects.create(node='CWKZ', state='unaudit', audit_people=cwk_obj.head_people, parent_id=obj)

        MaintainServerAuditRecord.objects.create(node='B', state='unaudit', audit_people=sbk_obj.leaders_id, parent_id=obj)
        if float(total_money) >= 200000:
            job_num = '6688'
        if float(total_money) < 200000:
            job_num = '6888'
        MaintainServerAuditRecord.objects.create(node='SJ/YZ', state='unaudit',
                                              audit_people=User.objects.get(job_number=job_num),
                                              parent_id=obj)                                    # 院长
        try:
            cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        except Exception as E:
            returnDict = {'code': 500, 'message': '系统未设置 ”财务支付“ 一职，请联系管理员设置'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        MaintainServerAuditRecord.objects.create(node='CWK', state='unaudit', audit_people=cn_obj, parent_id=obj)
        returnData = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class MaintainServerApplyListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'finance/maintain_server_apply_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'apply')  # apply 我的申请 audit 我的待办 already 我的已办

        objs = user.maintainserver_set.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'title': obj.title,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": "maintain_server_apply_draft_view?id=" + str(obj.id) if obj.state == 'draft' else "maintain_server_apply_detail_view?id=" + str(obj.id),
                      'state': obj.get_str_state(),
                      'financial': obj.financial,
                      'total_money': obj.total_money}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MaintainServerApplyDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get("id", None)
        obj = MaintainServer.objects.get(id=id)
        audit_dic = {}
        for audit_obj in obj.maintainserverauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if obj.state == 'seven' and obj.apply_user == request.user else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'seven'] and request.user == obj.apply_user else 'false',
                   'user_obj': User.objects.filter(group_id=1),
                   }
        return render(request, 'finance/maintain_server_apply_detail_view.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        obj = MaintainServer.objects.get(id=int(id))
        obj.current_audit_users.clear()
        obj.audit_users_already.add(request.user)
        if obj.state == 'one':
            audit_record = obj.maintainserverauditrecord_set.filter(node='SBKZ', state='unaudit').first()
            next_audit_record = obj.maintainserverauditrecord_set.filter(node='CWKZ', state='unaudit').first()
            if state == 'audit':
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'two':
            audit_record = obj.maintainserverauditrecord_set.filter(node='CWKZ', state='unaudit').first()
            next_audit_record = obj.maintainserverauditrecord_set.filter(node='B', state='unaudit').first()
            if state == 'audit':
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'three':
            audit_record = obj.maintainserverauditrecord_set.filter(node='B', state='unaudit').first()
            next_audit_record = obj.maintainserverauditrecord_set.filter(node='SJ/YZ', state='unaudit').first()
            if state == 'audit':
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'four':
            audit_record = obj.maintainserverauditrecord_set.filter(node='SJ/YZ', state='unaudit').first()
            next_audit_record = obj.maintainserverauditrecord_set.filter(node='CWK', state='unaudit').first()
            if state == 'audit':
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'seven'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'five':
            audit_record = obj.maintainserverauditrecord_set.filter(node='CWK', state='unaudit').first()
            if state == 'audit':
                obj_state = 'six'
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class MaintainServerApplyDarftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        obj = MaintainServer.objects.get(id=id)
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                             ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for
            atta_obj in
            Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   'department': request.user.company.name, 'obj': obj, 'file_list': file_list}
        return render(request, 'finance/maintain_server_apply_draft_index.html', context)

    def post(self, request):
        user = request.user
        id = request.POST.get('id', None)
        title = request.POST.get('title', None)         # 付款标题
        total_money = request.POST.get('total_money', 0)     # 付款总金额
        company = request.user.company     # 上传科室
        financial = request.POST.get('financial', '')
        fj_number = request.POST.get('fj_number', None)
        if id:
            obj = MaintainServer.objects.get(id=id)
            obj.title = title
            obj.total_money = total_money
            obj.financial = financial
            obj.state = 'draft'
            obj.save()
        else:
            obj = MaintainServer.objects.create(apply_user=user, state='draft',
                                             title=title, total_money=total_money,
                                             company=company, financial=financial, fj_number=fj_number,)
        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class MaintainServerApplyWriteView(View):
    def post(self, request):
        id = request.POST.get("id", None)
        obj = MaintainServer.objects.get(id=int(id))
        if obj.state != 'seven':
            returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        title = request.POST.get('title', None)
        total_money = request.POST.get('total_money', None)
        company = request.POST.get('company', None)
        financial = request.POST.get('financial', '')
        fj_number = request.POST.get('fj_number', None)
        obj.current_audit_users.clear()
        obj.state = 'one'
        if obj.maintainserverauditrecord_set.filter(node='SBKZ', state='unaudit').count() == 0:
            audit_record_obj = obj.maintainserverauditrecord_set.filter(node='SBKZ').first()
            MaintainServerAuditRecord.objects.create(node='SBKZ', state='unaudit',
                                                  audit_people=audit_record_obj.audit_people,
                                                  parent_id=obj)

        if obj.maintainserverauditrecord_set.filter(node='CWKZ', state='unaudit').count() == 0:
            audit_record_obj = obj.maintainserverauditrecord_set.filter(node='CWKZ').first()
            MaintainServerAuditRecord.objects.create(node='CWKZ', state='unaudit',
                                                  audit_people=audit_record_obj.audit_people,
                                                  parent_id=obj)

        if obj.maintainserverauditrecord_set.filter(node='B', state='unaudit').count() == 0:
            audit_record_obj = obj.maintainserverauditrecord_set.filter(node='B').first()
            MaintainServerAuditRecord.objects.create(node='B', state='unaudit',
                                                  audit_people=audit_record_obj.audit_people,
                                                  parent_id=obj)
        try:
            yz_obj = Staffing.objects.get(station='院长')
        except:
            returnDict = {'code': 500, 'message': '系统未设置 ”院长“ 一职，请联系管理员设置'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        try:
            sj_obj = Staffing.objects.get(station='书记')
        except:
            returnDict = {'code': 500, 'message': '系统未设置 ”书记“ 一职，请联系管理员设置'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.maintainserverauditrecord_set.filter(node='SJ/YZ').delete()
        MaintainServerAuditRecord.objects.create(parent_id=obj,
                                                 audit_people=yz_obj if int(total_money) < 200000 else sj_obj,
                                                 audit_note='', state='unaudit', node='SJ/YZ')

        if obj.maintainserverauditrecord_set.filter(node='CWK', state='unaudit').count() == 0:
            audit_record_obj = obj.maintainserverauditrecord_set.filter(node='CWK').first()
            MaintainServerAuditRecord.objects.create(node='CWK', state='unaudit',
                                                  audit_people=audit_record_obj.audit_people,
                                                  parent_id=obj)
        if title:
            obj.title = title
        if total_money:
            obj.total_money = total_money
        if company:
            obj.company = company
        if financial:
            obj.financial = financial
        if fj_number:
            obj.fj_number = fj_number
        audit_record_obj = obj.maintainserverauditrecord_set.filter(node='SBKZ').last()
        obj.current_audit_users.add(audit_record_obj.audit_people)
        obj.save()
        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class MaintainServerRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = MaintainServer.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'six':
                returnData = {'code': 500, 'message': '作废失败，只有未审批完毕的付款申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.maintainserverauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的付款申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'six':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的付款申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class LogisticsOfficeApplyView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        obj = {
            'payee': '',
            'payee_account': ''
        }

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   'obj': obj, 'uuid': uuid.uuid1()}
        return render(request, 'finance/logistics_office_apply_view.html', context)

    def post(self, request):
        # apply_user = request.user
        # company = request.user.company
        # id = request.POST.get('id', None)
        # daxie = request.POST.get('daxie', None)                                 # 大写
        # total_money = request.POST.get('total_money', 0)                        # 总金额
        # fj_number = request.POST.get('fj_number', None)
        # rask = request.POST.get('rask', None)                                   # 备注
        # payee = request.POST.get('payee', None)                                 # 收款单位
        # payee_account = request.POST.get('payee_account', None)                 # 收款账号
        # source_funds = request.POST.get('source_funds', None)                   # 经费来源
        # pay_reason = request.POST.get('pay_reason', None)                       # 付款事由
        # check_or_not = request.POST.get('check_or_not', None)                   # 是否会计核对
        # BankDeposit = request.POST.get('BankDeposit', None)                     # 开户行
        # xiugai = request.POST.get('xiugai', None)                               # 是否是管理员修改
        # # ************************************************ 保存操作记录 ************************************
        # try:
        #     RecordAndPush().OperationRecords(request, "合同付款")
        # except:
        #     pass
        # if id:
        #     obj = LogisticsOffice.objects.get(id=id)
        #     obj.BankDeposit = BankDeposit
        #     obj.state = 'one'
        #     obj.fund_type = "epiboly"
        #     obj.payee = payee
        #     obj.total_money = total_money
        #     obj.fj_number = fj_number
        #     obj.payee_account = payee_account
        #     obj.note = source_funds
        #     obj.pay_reason = pay_reason
        #     obj.daxie = daxie
        #     obj.rask = rask
        #     obj.save()
        #     message = '修改成功！'
        #     if not xiugai:
        #         obj.current_audit_users.clear()
        #         obj.logisticsofficeauditrecord_set.filter(state='unaudit').delete()
        # else:
        #     obj = LogisticsOffice.objects.create(apply_user=apply_user, state='one', fund_type="epiboly", payee=payee, payee_account=payee_account, total_money=total_money, company=company,
        #                                          fj_number=fj_number, note=source_funds, pay_reason=pay_reason, daxie=daxie, rask=rask, BankDeposit=BankDeposit)
        #     message = '创建成功！'
        #
        # if not xiugai:
        #     one_appave = apply_user.company.head_people
        #     try:
        #         htkj_obj = Staffing.objects.get(station='合同付款会计').post_personnel.all()
        #     except:
        #         returnDict = {'code': 500, 'message': '系统未设置 ”合同付款会计“ 一职，请联系管理员设置'}
        #         return HttpResponse(json.dumps(returnDict), content_type="application/json")
        #     check_flag = True
        #     if check_or_not == "1":
        #         for htkj in htkj_obj:
        #             obj.current_audit_users.add(htkj)
        #             LogisticsOfficeAuditRecord.objects.create(node='zero', state='unaudit', audit_people=htkj, parent_id=obj)
        #         obj.state = 'zero'
        #         check_flag = False
        #         obj.save()
        #     one_flag = True
        #     if one_appave != apply_user:
        #         LogisticsOfficeAuditRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, parent_id=obj)
        #         if check_flag:
        #             obj.current_audit_users.add(one_appave)
        #             obj.state = 'one'
        #             one_flag = False
        #             obj.save()
        #     two_appave = Company.objects.get(id=22).head_people
        #     LogisticsOfficeAuditRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, parent_id=obj)
        #     if check_flag and one_flag:
        #         obj.current_audit_users.add(two_appave)
        #         obj.state = 'two'
        #         obj.save()
        #     three_appave = Company.objects.get(id=23).head_people
        #     LogisticsOfficeAuditRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, parent_id=obj)
        #     four_appave = apply_user.company.leaders_id
        #     LogisticsOfficeAuditRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, parent_id=obj)
        #     LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Staffing.objects.get(station='工会主席').post_personnel.all().first(), parent_id=obj)
        #     try:
        #         cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        #     except:
        #         returnDict = {'code': 500, 'message': '系统未设置 ”财务支付“ 一职，请联系管理员设置'}
        #         return HttpResponse(json.dumps(returnDict), content_type="application/json")
        #     LogisticsOfficeAuditRecord.objects.create(node='six', state='unaudit', audit_people=cn_obj, parent_id=obj)
        #
        #     # ********************************************** 发送小程序推送 ******************************************
        #     topic_type = "合同付款"
        #     applicant = obj.apply_user.real_name
        #     ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        #     SubjectMatter = obj.pay_reason[:15] + "……" if len(obj.pay_reason) > 15 else obj.pay_reason
        #     for jj in obj.current_audit_users.all():
        #         try:
        #             RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        #         except:
        #             pass

        returnData = {'code': 400, 'message': "该流程已关闭，现已无法申请！"}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class LogisticsOfficeListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "table_name": 'finance_logisticsoffice'}
        return render(request, 'finance/logistics_office_list_view.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'apply')  # apply 我的申请 audit 我的待办 already 我的已办

        objs = user.logisticsoffice_set.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'pay_reason': obj.pay_reason,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='logistics_office_apply_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                      if obj.state == 'draft' else (f"<a href='logistics_office_apply_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                                                          if obj.state == 'stop' else f"<a href='logistics_office_apply_detail_view?id={obj.id}'>查看</a>"),
                      'state': obj.get_str_state(),
                      'total_money': obj.total_money}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class LogisticsOfficeApplyDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        try:
            cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        except:
            returnDict = {'code': 500, 'message': '系统未设置 ”财务支付“ 一职，请联系管理员设置'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj = LogisticsOffice.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.logisticsofficeauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.logisticsofficeauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if obj.state == 'eight' and obj.apply_user == request.user else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six", "zero"] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', "zero", "eight"] and request.user == obj.apply_user else 'false',
                   'user_obj': User.objects.filter(group_id=1),
                   'flow_dict': flow_dict, 'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/logistics_office_apply_detail_view.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "合同付款")
        except:
            pass
        obj = LogisticsOffice.objects.get(id=int(id))
        obj.current_audit_users.clear()
        obj.audit_users_already.add(request.user)
        if obj.state == 'zero':
            if state == 'audit':
                audit_record = None
                audit_list = obj.logisticsofficeauditrecord_set.filter(node='zero', state='unaudit')
                for zero in audit_list:
                    if request.user == zero.audit_people:
                        audit_record = zero
                if obj.logisticsofficeauditrecord_set.filter(node='one'):
                    obj_state = 'one'
                    next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='one', state='unaudit').first()
                else:
                    obj_state = 'two'
                    next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='two', state='unaudit').first()
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'one':
            audit_record = obj.logisticsofficeauditrecord_set.filter(node='one', state='unaudit').first()
            next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'two':
            audit_record = obj.logisticsofficeauditrecord_set.filter(node='two', state='unaudit').first()
            next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'three':
            audit_record = obj.logisticsofficeauditrecord_set.filter(node='three', state='unaudit').first()
            next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'four':
            audit_record = obj.logisticsofficeauditrecord_set.filter(node='four', state='unaudit').first()
            next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'five':
            audit_record = obj.logisticsofficeauditrecord_set.filter(node='five', state='unaudit').first()
            next_audit_record = obj.logisticsofficeauditrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = 'six'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'six':
            audit_record = obj.logisticsofficeauditrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "合同付款"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.pay_reason[:15] + "……" if len(obj.pay_reason) > 15 else obj.pay_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class LogisticsOfficeApplyDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        obj = LogisticsOffice.objects.get(id=id)
        if obj.fj_number:
            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                                 ""),
                 "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for
                atta_obj in
                Topicsattachments.objects.filter(topics_number=obj.fj_number)]
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, 'obj': obj, 'file_list': file_list}
        else:
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, 'obj': obj, 'uuid': uuid.uuid1()}
        return render(request, 'finance/logistics_office_apply_draft_index.html', context)

    def post(self, request):
        apply_user = request.user
        id = request.POST.get('id', None)
        daxie = request.POST.get('daxie', None)  # 大写
        total_money = request.POST.get('total_money', "0")  # 总金额
        fj_number = request.POST.get('fj_number', None)
        rask = request.POST.get('rask', None)  # 备注
        payee = request.POST.get('payee', None)  # 收款单位
        payee_account = request.POST.get('payee_account', None)  # 收款账号
        source_funds = request.POST.get('source_funds', None)  # 经费来源
        pay_reason = request.POST.get('pay_reason', None)  # 付款事由
        submit = request.POST.get('submit', None)
        check_or_not = request.POST.get('check_or_not', None)  # 是否会计核对
        BankDeposit = request.POST.get('BankDeposit', '')  # 开户行
        if not total_money.strip():
            total_money = 0
        if id:
            obj = LogisticsOffice.objects.get(id=id)
            obj.apply_user = request.user
            obj.fund_type = "epiboly"
            obj.payee = payee
            obj.total_money = total_money
            obj.company = request.user.company
            obj.fj_number = fj_number
            obj.BankDeposit = BankDeposit
            obj.payee_account = payee_account
            obj.note = source_funds
            obj.pay_reason = pay_reason
            obj.daxie = daxie
            obj.rask = rask
            obj.state = 'draft'
            obj.save()
        else:
            obj = LogisticsOffice.objects.create(apply_user=request.user, state='draft', fund_type="epiboly", payee=payee,
                                                 payee_account=payee_account, total_money=total_money, company=request.user.company,
                                                 fj_number=fj_number, note=source_funds, pay_reason=pay_reason,
                                                 daxie=daxie, rask=rask, BankDeposit=BankDeposit)

        if submit:
            one_appave = apply_user.company.head_people

            try:
                htkj_obj = Staffing.objects.get(station='合同付款会计').post_personnel.all()
            except:
                returnDict = {'code': 500, 'message': '系统未设置 ”合同付款会计“ 一职，请联系管理员设置'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

            check_flag = True
            if check_or_not == "1":
                for htkj in htkj_obj:
                    obj.current_audit_users.add(htkj)
                    LogisticsOfficeAuditRecord.objects.create(node='zero', state='unaudit', audit_people=htkj, parent_id=obj)
                obj.state = 'zero'
                check_flag = False
                obj.save()

            one_flag = True
            if one_appave != apply_user:
                LogisticsOfficeAuditRecord.objects.create(node='one', state='unaudit', audit_people=one_appave, parent_id=obj)
                if check_flag:
                    obj.current_audit_users.add(one_appave)
                    obj.state = 'one'
                    one_flag = False
                    obj.save()

            two_appave = Company.objects.get(id=22).head_people
            LogisticsOfficeAuditRecord.objects.create(node='two', state='unaudit', audit_people=two_appave, parent_id=obj)
            if check_flag and one_flag:
                obj.current_audit_users.add(two_appave)
                obj.state = 'two'
                obj.save()

            three_appave = Company.objects.get(id=23).head_people
            LogisticsOfficeAuditRecord.objects.create(node='three', state='unaudit', audit_people=three_appave, parent_id=obj)

            four_appave = apply_user.company.leaders_id
            LogisticsOfficeAuditRecord.objects.create(node='four', state='unaudit', audit_people=four_appave, parent_id=obj)

            if float(total_money.replace(",", "")) < 10000:
                LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Company.objects.get(id=23).leaders_id, parent_id=obj)
            elif 1000 <= float(total_money.replace(",", "")) < 200000:
                LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=obj)
            else:
                LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit',
                                                          audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=obj)

            try:
                cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
            except:
                returnDict = {'code': 500, 'message': '系统未设置 ”财务支付“ 一职，请联系管理员设置'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            LogisticsOfficeAuditRecord.objects.create(node='six', state='unaudit', audit_people=cn_obj, parent_id=obj)
            returnData = {'code': 200, 'message': '创建成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class LogisticsOfficeRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = LogisticsOffice.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的请假申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.logisticsofficeauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的请假申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的流程不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class LogisticsOfficeWriteView(View):
    def post(self, request):
        apply_user = request.user
        company = request.user.company
        id = request.POST.get("id", None)
        obj = LogisticsOffice.objects.get(id=int(id))
        if obj.state != 'seven':
            returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        fund_type = request.POST.get('fund_type', 'materials')
        total_money = request.POST.get('total_money', 0)
        fj_number = request.POST.get('fj_number', None)
        payee = request.POST.get('payee', None)
        payee_account = request.POST.get('payee_account', None)
        note = request.POST.get('note', None)
        obj.fund_type = fund_type
        obj.total_money = total_money
        obj.note = note
        obj.payee = payee
        obj.state = 'one'
        obj.fj_number = fj_number
        obj.payee_account = payee_account
        obj.current_audit_users.clear()
        obj.save()

        zwk_obj = Company.objects.get(id=27)
        if apply_user.company.head_people:
            obj.current_audit_users.add(zwk_obj.head_people)
        else:
            returnDict = {'code': 500, 'message': '创建失败！申请人科室未配置主任。'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        LogisticsOfficeAuditRecord.objects.create(node='one', state='unaudit',
                                                  audit_people=zwk_obj.head_people, parent_id=obj)
        try:
            cwk_obj = Staffing.objects.get(station='财务科会计')
        except:
            returnDict = {'code': 500, 'message': '系统未设置 ”财务科会计“ 一职，请联系管理员设置'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        sjk_obj = Company.objects.get(id=22)
        if fund_type == 'materials':
            LogisticsOfficeAuditRecord.objects.create(node='two', state='unaudit',
                                                      audit_people=cwk_obj, parent_id=obj)
        else:
            LogisticsOfficeAuditRecord.objects.create(node='two', state='unaudit',
                                                      audit_people=sjk_obj.head_people, parent_id=obj)

        LogisticsOfficeAuditRecord.objects.create(node='three', state='unaudit',
                                                  audit_people=Company.objects.get(id=23).head_people, parent_id=obj)
        LogisticsOfficeAuditRecord.objects.create(node='four', state='unaudit',
                                                  audit_people=company.leaders_id,
                                                  parent_id=obj)

        if float(total_money) < 10000:
            LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit',
                                                      audit_people=Company.objects.get(id=23).leaders_id, parent_id=obj)
        elif 1000 <= float(total_money) < 200000:
            LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit',
                                                      audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=obj)
        else:
            LogisticsOfficeAuditRecord.objects.create(node='five', state='unaudit',
                                                      audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=obj)
        try:
            cn_obj = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        except:
            returnDict = {'code': 500, 'message': '系统未设置 ”财务支付“ 一职，请联系管理员设置'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        LogisticsOfficeAuditRecord.objects.create(node='six', state='unaudit', audit_people=cn_obj, parent_id=obj)

        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 差旅报销列表
class ReimbursementList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "table_name": 'finance_travelreimbursement'}
        return render(request, 'finance/reimbursement_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_value = request.POST.get("search_value", None)
        if search_value:
            objs = TravelReimbursement.objects.filter(Q(user__real_name__contains=search_value) | Q(user__department__contains=search_value), applicat=request.user)
        else:
            objs = TravelReimbursement.objects.filter(applicat=request.user)

        objs = objs.order_by('-create_time')
        data_list = [{'id': obj.id, 'business_matter': obj.business_matter, 'travel_people': ", ".join([i.real_name for i in obj.travel_people.all()]),
                      'apply_time': obj.apply_time, 'vote_reluse': '是' if obj.vote_reluse == 'yes' else '否', 'business_days': obj.business_days,
                      'total': obj.total, 'state': obj.get_state_str(), 'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
                      'url': f"<a href='travel_reimbursement.html?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                      if obj.get_state_str() == '草稿' else (f"<a href='travel_approval.html?id={obj.id}'>查看</a> | <a href='travel_approval.html?revise=true&id={obj.id}'>修改</a>"
                                                           if (obj.can_revise == '1' and obj.state in ['one', 'nine', 'two', 'three'])
                                                           else (f"<a href='travel_approval.html?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                                                                 if obj.state == 'stop' else f"<a href='travel_approval.html?id={obj.id}'>查看</a>"))}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class TravelReimBursement(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        trave_id = request.GET.get("id", None)
        out_obj = OutgoingCadresData.objects.filter(relevance="0", state="seven").filter(Q(outgoing_person=request.user) | Q(apply_user=request.user)).distinct().order_by("-create_time")                # 中层干部外出
        Tra_obj = TravelApply.objects.filter(relevance="0", state="five").filter(Q(travel_users=request.user) | Q(apply_user=request.user)).distinct().order_by("-create_time")               # 差旅申请
        Veh_obj = VehicleApply.objects.filter(relevance="0", state="cgb").filter(Q(apply_user=request.user) | Q(field_leader_numbers__contains=request.user.job_number)).distinct().order_by("-create_time")                      # 用车申请
        if trave_id:
            trave_obj = TravelReimbursement.objects.get(id=int(trave_id))
            data_obj = {'apply_time': trave_obj.apply_time, "travel_people": ", ".join([i.real_name for i in trave_obj.travel_people.all()]),
                        "vote_reluse": trave_obj.vote_reluse,
                        "total_daxie": trave_obj.total_daxie, 'business_days': trave_obj.business_days,
                        'hotel_expense': trave_obj.hotel_expense, 'business_matter': trave_obj.business_matter,
                        'traffic_expense': trave_obj.traffic_expense, 'payee': trave_obj.payee,
                        'remarks': trave_obj.remarks, 'total': trave_obj.total,
                        'TotalList': json.loads(json.loads(trave_obj.reimburse_dict))['TotalList'],
                        'OtherList': json.loads(json.loads(trave_obj.reimburse_dict))['OtherList'],
                        'is_edit': 'true' if trave_obj.get_state_str() == '拒绝' else 'false',
                        'sp_company': trave_obj.AuditDepartment}
            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=trave_obj.uuid)]
            audit_dic, flow_dict = {}, {}
            for audit_obj in trave_obj.travelreimbursementauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state,
                                                      'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime(
                                                          "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(
                                                          audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in trave_obj.travelreimbursementauditrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                                 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                       'apply': trave_obj.applicat.real_name,
                       "company": trave_obj.applicat.company.name, 'uuid': trave_obj.uuid, 'file_list': file_list, 'invoice_number': ','.join([ll.invoice_number for ll in TravelReimbursementInvoiceNumber.objects.filter(parent_id=trave_obj)]),
                       'data_obj': data_obj, "audit_dic": audit_dic, "relevance_list": VehicleApply.objects.filter(id__in=json.loads(trave_obj.relevance_list)),
                       "is_audit": "true" if trave_obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'nine'] and request.user in trave_obj.current_audit_users.all() else 'false',
                       "is_edit": "true" if trave_obj.state == 'draft' and request.user == trave_obj.applicat else 'false',
                       "is_stop": "true" if trave_obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'nine', 'eight'] and request.user == trave_obj.applicat else 'false',
                       "id": trave_id, "trave_obj": trave_obj, "flow_dict": flow_dict, "out_obj": out_obj, "Tra_obj": Tra_obj, "Veh_obj": Veh_obj,
                       "file_path": Topicsattachments.objects.filter(topics_number=trave_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=trave_obj.uuid) else ""}

            return render(request, 'finance/travel_reimbursement.html', context)
        apply_time = datetime.now().strftime("%Y-%m-%d %H:%M")
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'uuid': uuid.uuid1(), "apply_time": apply_time, "out_obj": out_obj, "Tra_obj": Tra_obj, "Veh_obj": Veh_obj}
        return render(request, 'finance/travel_reimbursement.html', context)

    def post(self, request):
        apply_time = request.POST.get("apply_time", None)                           # 申请时间
        travel_people = request.POST.get("travel_people", None)                     # 出差人
        vote_reluse = request.POST.get("vote_reluse", None)                         # 是否派车
        business_days = request.POST.get("business_days", None)                     # 出差天数
        business_matter = request.POST.get("business_matter", None)                 # 出差事由
        remarks = request.POST.get("remarks", None)                                 # 备注
        total = request.POST.get("total", None)                                     # 合计
        total_daxie = request.POST.get("total_daxie", None)                         # 大写
        payee = request.POST.get("payee", None)                                     # 收款人
        uuid = request.POST.get("uuid", None)
        reimburse_dict = request.POST.get("reimburse_dict", None)                   # 报销JSON
        sp_people = request.POST.get("sp_people", None)                             # 审核科室
        draft = request.POST.get("draft", None)                                     # 是否草稿
        travel_id = request.POST.get("travel_id", None)                             # 流程ID
        SourceFunds = request.POST.get("SourceFunds", None)                         # 流程ID
        invoice_number = request.POST.get("invoice_number", "")                     # 发票号
        xiugai = request.POST.get("xiugai", None)                                   # 修改
        revise = request.POST.get("revise", None)                                   # 未审批是否可修改
        tar_id = request.POST.get("tar_id", None)                                   # 差旅申请流程ID
        veh_id = request.POST.get("veh_id", None)                                   # 用车流程ID
        out_id = request.POST.get("out_id", None)                                   # 中层干部外出流程ID
        veh_list = request.POST.get("veh_list", [])
        flow_type = request.POST.get("flow_type", "")
        invoice_number = invoice_number.replace("，", ',')

        if not flow_type:
            old_obj = TravelReimbursement.objects.filter(business_matter=business_matter)
            if old_obj.count():
                if invoice_number.split(",")[0] != "无":
                    number_obj_old = TravelReimbursementInvoiceNumber.objects.filter(~Q(parent_id__state='draft'), parent_id=old_obj.last(), invoice_number=invoice_number.split(",")[0]).count()
                    if number_obj_old:
                        returnData = {'code': 400, 'message': '该申请事由与对应发票号已发起报销，无需重复报销！'}
                        return HttpResponse(json.dumps(returnData), content_type="application/json")

            if draft == '0' and invoice_number:
                for kk in invoice_number.split(","):
                    if kk != "无":
                        old_obj_count = TravelReimbursementInvoiceNumber.objects.filter(~Q(parent_id__state='draft'), invoice_number=kk).count()
                        if old_obj_count:
                            returnData = {'code': 400, 'message': '发票号所对应发票已报销，不能重复报销！'}
                            return HttpResponse(json.dumps(returnData), content_type="application/json")

        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "差旅报销")
        except:
            pass
        # 获取出差人
        travel_jobnumber = re.findall('\((.*?)\)', travel_people)
        travel_users_objs = User.objects.filter(job_number__in=travel_jobnumber)
        tar_obj = TravelApply.objects.get(id=int(tar_id)) if tar_id else ""
        veh_obj = VehicleApply.objects.get(id=int(veh_id)) if veh_id else ""
        out_obj = OutgoingCadresData.objects.get(id=int(out_id)) if out_id else ""
        if draft == '0':
            status = 'one'
        else:
            status = 'draft'

        if travel_id:
            print("============================================开始修改============================================", payee)
            obj = TravelReimbursement.objects.get(id=int(travel_id))
            if travel_people and travel_users_objs:
                obj.travel_people.clear()
                for i in travel_users_objs:
                    obj.travel_people.add(i)

            obj.business_matter = business_matter
            if payee:
                obj.payee = payee
            obj.AuditDepartment = sp_people
            obj.vote_reluse = vote_reluse
            obj.business_days = business_days
            obj.hotel_expense = ""
            obj.traffic_expense = ""
            obj.SourceFunds = SourceFunds
            obj.total_daxie = total_daxie
            obj.remarks = remarks
            obj.total = total
            data_dict = json.loads(reimburse_dict)
            try:
                if data_dict["TotalList"][0]['A']:
                    obj.reimburse_dict = json.dumps(reimburse_dict)
            except Exception as e:
                print('误删除操作数据还原！', e)
            obj.save()
            if not xiugai:
                obj.current_audit_users.clear()
                obj.travelreimbursementauditrecord_set.filter(state='unaudit').delete()
                obj.travelreimbursementinvoicenumber_set.all().delete()
                obj.save()

            if revise:
                obj.current_audit_users.clear()
                obj.travelreimbursementauditrecord_set.all().delete()

        else:
            # 保存主表
            obj = TravelReimbursement.objects.create(business_matter=business_matter, state=status, payee=payee, AuditDepartment=sp_people,
                SourceFunds=SourceFunds, apply_time=apply_time, vote_reluse=vote_reluse, total_daxie=total_daxie, business_days=business_days, hotel_expense="", traffic_expense="",
                reimburse_dict=json.dumps(reimburse_dict), remarks=remarks, total=total, uuid=uuid, applicat=request.user, company=request.user.company
            )
        if tar_obj:
            obj.relevance = tar_obj
        if veh_obj:
            obj.relevance_car = veh_obj
            obj.relevance_list = veh_list
        if out_obj:
            obj.relevance_zc = out_obj
        for i in travel_users_objs:
            obj.travel_people.add(i)
        obj.save()
        if invoice_number:
            for invoice in invoice_number.split(","):
                if invoice != "无":
                    TravelReimbursementInvoiceNumber.objects.create(parent_id=obj, invoice_number=invoice)

        if draft == '0':
            if not total.strip():
                returnData = {'code': 500, 'message': '报销金额为0，请添加报销项！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            try:
                two_audit_people = Staffing.objects.get(station="财务出纳").post_personnel.all().first()
            except Exception as E:
                returnData = {'code': 500, 'message': '请创建财务出纳的角色！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            try:
                six_audit_people = Staffing.objects.get(station="财务支付").post_personnel.all().first()
            except Exception as E:
                returnData = {'code': 500, 'message': '请创建财务支付的角色！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")

            cwk = Company.objects.get(id=23)

            TravelReimbursementAuditRecord.objects.create(node='two', state='unaudit', audit_people=two_audit_people, parent_id=obj)
            obj.current_audit_users.add(two_audit_people)  # 创建当前审批人
            obj.state = "two"

            if SourceFunds == '1':
                kjk = Company.objects.get(id=14)
                kjk_director = kjk.head_people
                TravelReimbursementAuditRecord.objects.create(node='nine', state='unaudit', audit_people=kjk_director, parent_id=obj)
            elif SourceFunds == '2':
                gwk = Company.objects.get(id=19)
                gwk_director = gwk.head_people
                TravelReimbursementAuditRecord.objects.create(node='nine', state='unaudit', audit_people=gwk_director, parent_id=obj)
            else:
                pass
            if tar_obj:
                tar_obj.relevance = "1"
                tar_obj.save()
            if veh_obj:
                veh_obj.relevance = "1"
                VehicleApply.objects.filter(id__in=json.loads(veh_list)).update(relevance="1")
                veh_obj.save()

            if out_obj:
                out_obj.relevance = "1"
                out_obj.save()

            three_setp = Company.objects.get(id=22).head_people
            TravelReimbursementAuditRecord.objects.create(node='three', state='unaudit', audit_people=three_setp, parent_id=obj)
            TravelReimbursementAuditRecord.objects.create(node='four', state='unaudit', audit_people=cwk.head_people, parent_id=obj)
            TravelReimbursementAuditRecord.objects.create(node='six', state='unaudit', audit_people=six_audit_people, parent_id=obj)
            obj.save()
            # ********************************************** 发送小程序推送 ******************************************
            topic_type = "差旅报销"
            applicant = obj.applicat.real_name
            ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
            SubjectMatter = obj.business_matter[:15] + "……" if len(obj.business_matter) > 15 else obj.business_matter
            for jj in obj.current_audit_users.all():
                try:
                    RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
                except:
                    pass
        returnData = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 差旅详情及审批
class TravelApproval(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        trave_id = request.GET.get("id", None)
        revise = request.GET.get("revise", None)
        two_audit_people = Staffing.objects.get(station="财务出纳").post_personnel.all().first()
        if int(trave_id) > 58:
            trave_obj = TravelReimbursement.objects.get(id=int(trave_id))
            travel_people_list = [f'{i.real_name}({i.company.name})' for i in trave_obj.travel_people.all().order_by("id")]
            # if trave_obj.id == 134:
            #     OnePeople = travel_people_list[0]
            #     FivePeople = travel_people_list[5]
            #     travel_people_list.remove("陈勇")
            #     travel_people_list[0] = travel_people_list[1]
            #     travel_people_list[1] = OnePeople
            #     travel_people_list.insert(-1, '陈勇')
            data_obj = {'apply_time': trave_obj.apply_time, "travel_people": ", ".join(travel_people_list),
                        "vote_reluse": trave_obj.vote_reluse,
                        "total_daxie": trave_obj.total_daxie, 'business_days': trave_obj.business_days,
                        'hotel_expense': trave_obj.hotel_expense, 'business_matter': trave_obj.business_matter,
                        'traffic_expense': trave_obj.traffic_expense, 'payee': trave_obj.payee,
                        'remarks': trave_obj.remarks, 'total': trave_obj.total,
                        'TotalList': json.loads(json.loads(trave_obj.reimburse_dict))['TotalList'],
                        'OtherList': json.loads(json.loads(trave_obj.reimburse_dict))['OtherList'],
                        'is_edit': 'true' if trave_obj.get_state_str() == '拒绝' else 'false',
                        'sp_company': trave_obj.AuditDepartment}
            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=trave_obj.uuid)]
            audit_dic, flow_dict = {}, {}
            for audit_obj in trave_obj.travelreimbursementauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    if audit_obj.node != 'two':
                        if audit_obj.state != "unaudit":
                            audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                          'state_display': audit_obj.get_state_display(),
                                                          'state': audit_obj.state,
                                                          'node': audit_obj.node,
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime(
                                                              "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(
                                                              audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
                    else:
                        audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                          'state_display': audit_obj.get_state_display(),
                                                          'state': audit_obj.state,
                                                          'node': audit_obj.node,
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime(
                                                              "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(
                                                              audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in trave_obj.travelreimbursementauditrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                                 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            if 'two' in audit_dic and len(audit_dic['two']) > 2:
                audit_dic['two'] = audit_dic['two'][-2:]
            out_obj = request.user.outgoingcadresdata_set.filter(relevance="0", state="seven").order_by("-create_time")  # 中层干部外出
            Tra_obj = request.user.travelapply_set.filter(relevance="0", state="five").order_by("-create_time")  # 差旅申请
            Veh_obj = request.user.vehicleapply_set.filter(relevance="0", state="cgb").order_by("-create_time")  # 用车申请
            invoice_number_list = [ll.invoice_number for ll in TravelReimbursementInvoiceNumber.objects.filter(parent_id=trave_obj)]
            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                       'apply': trave_obj.applicat.real_name, 'relevance_list': VehicleApply.objects.filter(id__in=json.loads(trave_obj.relevance_list)),
                       "company": trave_obj.applicat.company.name, 'uuid': trave_obj.uuid, 'file_list': file_list,
                       'data_obj': data_obj, "audit_dic": audit_dic, 'out_obj': out_obj, 'Tra_obj': Tra_obj, 'Veh_obj': Veh_obj,
                       "is_audit": "true" if trave_obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'nine'] and request.user in trave_obj.current_audit_users.all() else 'false',
                       "is_edit": "true" if (trave_obj.state == 'eight' and request.user == trave_obj.applicat) or revise else 'false',
                       "is_stop": "true" if trave_obj.state == 'one' and request.user == two_audit_people else 'false',
                       "id": trave_id, "trave_obj": trave_obj, "flow_dict": flow_dict, "revise": revise,
                       'invoice_number': ','.join(invoice_number_list) if invoice_number_list else "无",
                       "file_path": Topicsattachments.objects.filter(topics_number=trave_obj.uuid).first().pdf_path.replace(
                           "\\", "/") if Topicsattachments.objects.filter(topics_number=trave_obj.uuid) else ""}
            return render(request, 'finance/travel_approval.html', context)

        else:
            trave_obj = TravelReimbursement.objects.get(id=int(trave_id))
            data_obj = {'apply_time': trave_obj.apply_time,
                        "travel_people": ", ".join([i.real_name for i in trave_obj.travel_people.all()]),
                        "vote_reluse": trave_obj.vote_reluse, "total_daxie": trave_obj.total_daxie,
                        'business_days': trave_obj.business_days, 'hotel_expense': trave_obj.hotel_expense,
                        'business_matter': trave_obj.business_matter, 'traffic_expense': trave_obj.traffic_expense,
                        'payee': trave_obj.payee,
                        'remarks': trave_obj.remarks, 'total': trave_obj.total,
                        'reimburse_dict': json.loads(json.loads(trave_obj.reimburse_dict)),
                        'is_edit': 'true' if trave_obj.get_state_str() == '拒绝' else 'false'}
            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                     os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=trave_obj.uuid)]
            audit_dic, flow_dict = {}, {}
            for audit_obj in trave_obj.travelreimbursementauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    if audit_obj.node != 'two':
                        if audit_obj.state != "unaudit":
                            audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                          'state_display': audit_obj.get_state_display(),
                                                          'state': audit_obj.state,
                                                          'node': audit_obj.node,
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime(
                                                              "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(
                                                              audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
                    else:
                        audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                          'state_display': audit_obj.get_state_display(),
                                                          'state': audit_obj.state,
                                                          'node': audit_obj.node,
                                                          'node_display': audit_obj.get_node_display(),
                                                          'audit_note': audit_obj.audit_note,
                                                          'audit_time': audit_obj.update_time.strftime(
                                                              "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                          'signature_picture': '/media/' + str(
                                                              audit_obj.audit_people.signature_picture) if (
                                                                  audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in trave_obj.travelreimbursementauditrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                                 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            if 'two' in audit_dic and len(audit_dic['two']) > 2:
                audit_dic['two'] = audit_dic['two'][-2:]
            payment_obj = ['data:image/jpeg;base64,' + i.imgs.replace(" ", "+") for i in trave_obj.travelreimbursementpayment_set.all()]
            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                       'apply': trave_obj.applicat.real_name,
                       "company": trave_obj.applicat.company.name, 'uuid': trave_obj.uuid, 'file_list': file_list,
                       'data_obj': data_obj, "audit_dic": audit_dic,
                       "is_audit": "true" if trave_obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'nine'] and request.user in trave_obj.current_audit_users.all() else 'false',
                       "is_edit": "true" if (trave_obj.state == 'eight' and request.user == trave_obj.applicat) or revise else 'false',
                       "is_stop": "true" if trave_obj.state == 'one' and request.user == two_audit_people else 'false',
                       "payment_obj": payment_obj,
                       "id": trave_id, "trave_obj": trave_obj, "flow_dict": flow_dict, "revise": revise,
                       "file_path": Topicsattachments.objects.filter(topics_number=trave_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(
                           topics_number=trave_obj.uuid) else ""}
            return render(request, 'finance/travel_approval1.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        ReimbursementAmount = request.POST.get("ReimbursementAmount", '')           # 实际报销金额

        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "差旅报销")
        except:
            pass

        obj = TravelReimbursement.objects.get(id=int(id))
        if not obj.travelreimbursementauditrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 400, 'message': '流程已审核，无需重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.current_audit_users.clear()

        if obj.state == 'one':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="two", state='unaudit').first()
                obj_state = "two"
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)
            obj.audit_users_already.add(request.user)
            obj.state = obj_state
            obj.save()

        elif obj.state == 'nine':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='nine', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.travelreimbursementauditrecord_set.filter(node='two', state='unaudit'):
                    next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="two", state='unaudit').first()
                    obj_state = "two"
                else:
                    next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="three", state='unaudit').first()
                    obj_state = "three"
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)
            obj.audit_users_already.add(request.user)
            obj.state = obj_state
            obj.save()

        elif obj.state == 'two':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.travelreimbursementauditrecord_set.filter(node='nine', state='unaudit'):
                    next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="nine", state='unaudit').first()
                    obj_state = "nine"
                else:
                    next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="three", state='unaudit').first()
                    obj_state = "three"
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)
            obj.audit_users_already.add(request.user)
            obj.state = obj_state
            obj.save()

        elif obj.state == 'three':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="four", state='unaudit').first()
                obj_state = "four"
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)
            obj.audit_users_already.add(request.user)
            obj.state = obj_state
            obj.save()

        elif obj.state == 'four':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.travelreimbursementauditrecord_set.filter(node="five", state='unaudit'):
                    next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="five", state='unaudit').first()
                    obj_state = "five"
                else:
                    next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="six", state='unaudit').first()
                    obj_state = "six"
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)
            obj.audit_users_already.add(request.user)
            obj.state = obj_state
            obj.save()

        elif obj.state == 'five':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_record = obj.travelreimbursementauditrecord_set.filter(node="six", state='unaudit').first()
                obj_state = "six"
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)

        elif obj.state == 'six':
            audit_record = obj.travelreimbursementauditrecord_set.filter(node='six', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                obj_state = "seven"
                try:
                    if obj.SourceFunds == '1':
                        headers = {
                            "Content-Type": 'application/json'
                        }
                        post_data = {
                            'key': 'hOJYdf7WoMTZV06Q',
                            'department_name': obj.company.name,
                            'time': obj.create_time.strftime("%Y-%m-%d"),
                            'amount': float(ReimbursementAmount.replace(",", '')) / 10000,
                            'agent_name': obj.applicat.real_name,
                            'reason': obj.business_matter
                        }
                        req = requests.post(url=post_url, headers=headers, data=json.dumps(post_data))
                        print(req.text)
                except:
                    print("同步更新出错")
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.applicat)

        else:
            returnData = {'code': 400, 'message': '流程状态出错了！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()

        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "差旅报销"
        applicant = obj.applicat.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.business_matter[:15] + "……" if len(obj.business_matter) > 15 else obj.business_matter
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 差旅撤回、中止等操作
class TravelRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = TravelReimbursement.objects.get(id=int(id))
        if obj.relevance:
            obj.relevance.relevance = '0'
            obj.relevance.save()
        if obj.relevance_car:
            obj.relevance_car.relevance = '0'
            obj.relevance_car.save()
        if obj.relevance_zc:
            obj.relevance_zc.relevance = '0'
            obj.relevance_zc.save()
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的请假申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.travelreimbursementauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的请假申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的请假申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class DimissionApplyView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name,
                   'position': request.user.post,
                   "department": request.user.company.name,
                   'job_number': request.user.job_number,
                   "degree": request.user.first_degree,
                   "tel_num": request.user.mobile,
                   "uuid": uuid.uuid1(),
                   'rank': request.user.rank,
                   "is_flag": "true" if request.user.group.id not in [1, 2, 3, 4, 5] else 'false',
                   }

        return render(request, 'finance/dimission_apply_view.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        user = request.user
        company = request.user.company
        job_number = request.user.job_number
        rank = request.user.rank        # 职称
        education = request.user.first_degree    # 学历
        tel_num = request.user.mobile       # 联系方式
        hiredate = request.POST.get('hiredate', None)   # 入职时间
        dimission_time = request.POST.get('dimission_time', None)   # 离职时间
        dimission_note = request.POST.get('dimission_note', None)   # 离职原因
        fj_number = request.POST.get('fj_number', None)
        people_type = request.POST.get('people_type', '')

        if id:
            obj = Dimission.objects.get(id=id)
            obj.user = user
            obj.job_number = job_number
            obj.rank = rank
            obj.education = education
            obj.company = company
            obj.fj_number = fj_number
            obj.tel_num = tel_num
            obj.hiredate = hiredate
            obj.dimission_time = dimission_time
            obj.dimission_note = dimission_note
            obj.people_type = people_type
            obj.save()
        else:

            obj = Dimission.objects.create(user=user, job_number=job_number, rank=rank, education=education, tel_num=tel_num, company=company,
            fj_number=fj_number, hiredate=hiredate, dimission_time=dimission_time, dimission_note=dimission_note, people_type=people_type)

        RskLeader = Company.objects.get(id=16).head_people
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='zero', audit_people=RskLeader)
        obj.current_audit_users.add(RskLeader)
        obj.state = "zero"

        head_department = company.head_people
        if user != head_department:
            DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='one', audit_people=head_department)

        if people_type == '2':
            two_step = Company.objects.get(id=13).head_people
            DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='two', audit_people=two_step)
            DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=two_step, node_name="医务科")

        if people_type == '3':
            two_step = Company.objects.get(id=15).head_people
            DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='two', audit_people=two_step)
            DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=two_step, node_name="护理部")

        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='three', audit_people=company.leaders_id)

        four_step = Company.objects.get(id=16).leaders_id
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='four', audit_people=four_step)

        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=3).head_people, node_name="党委办公室")
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=18).head_people, node_name="监察室")
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=80).head_people, node_name="医院办公室")
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=7).head_people, node_name="工会办公室")
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=14).head_people, node_name="科教科")
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=17).head_people, node_name="宣传科")
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=27).head_people, node_name="总务科")
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=30).head_people, node_name="膳食委员会")
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=26).head_people, node_name="设备科")
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=31).head_people, node_name="网络信息科")
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=24).head_people, node_name="病案统计科")
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=24).head_people, node_name="图书室")
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=16).head_people, node_name="人事科")

        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='six', audit_people=Company.objects.get(id=10).head_people)
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node='seven', audit_people=Company.objects.get(id=23).head_people)

        obj.save()
        returnData = {'code': 200, 'message': '创建成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class DimissionApplyListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'table_name': 'finance_dimission'}
        return render(request, 'finance/dimission_apply_list_view.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'apply')  # apply 我的申请 audit 我的待办 already 我的已办

        objs = Dimission.objects.filter(user=request.user).order_by('-create_time')
        data_list = [{'id': obj.id,
                      'dimission_note': obj.dimission_note,
                      'hiredate': obj.hiredate.strftime("%Y-%m-%d"),
                      'rank': obj.rank, 'people_type': "行管" if obj.people_type == '1' else '医技/临床' if obj.people_type == '2' else "护理",
                      'date': obj.create_time.strftime("%Y-%m-%d"), ""
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='dimission_apply_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                      if obj.state == 'draft' else (
                          f"<a href='dimission_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                          if obj.state == 'stop' else f"<a href='dimission_detail_view?id={obj.id}'>查看</a>"),
                      'state': obj.get_state_str(), "title": "离职申请"}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class DimissionApplyDarftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        obj = Dimission.objects.get(id=id)
        if obj.fj_number:
            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                                 ""),
                 "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for
                atta_obj in
                Topicsattachments.objects.filter(topics_number=obj.fj_number)]
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, 'obj': obj, 'file_list': file_list,
                       "is_flag": "true" if request.user.group.id not in [1, 2, 3, 4, 5] else 'false'}
        else:
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, 'obj': obj, 'uuid': uuid.uuid1(),
                       "is_flag": "true" if request.user.group.id not in [1, 2, 3, 4, 5] else 'false'}
        return render(request, 'finance/dimission_apply_draft_index.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        user = request.user
        company = request.user.company
        job_number = request.user.job_number
        rank = request.user.rank  # 职称
        education = request.user.first_degree  # 学历
        tel_num = request.user.mobile  # 联系方式
        hiredate = request.POST.get('hiredate', None)  # 入职时间
        dimission_time = request.POST.get('dimission_time', None)  # 离职时间
        dimission_note = request.POST.get('dimission_note', None)  # 离职原因
        fj_number = request.POST.get('fj_number', None)
        people_type = request.POST.get('people_type', '')

        if id:
            obj = Dimission.objects.get(id=id)
            obj.user = user
            obj.job_number = job_number
            obj.rank = rank
            obj.education = education
            obj.company = company
            obj.fj_number = fj_number
            obj.tel_num = tel_num
            obj.hiredate = hiredate
            obj.dimission_time = dimission_time
            obj.dimission_note = dimission_note
            obj.people_type = people_type
            obj.save()
        else:
            obj = Dimission.objects.create(user=user, job_number=job_number, rank=rank, education=education,
                                           tel_num=tel_num, company=company,
                                           fj_number=fj_number, hiredate=hiredate, dimission_time=dimission_time,
                                           dimission_note=dimission_note, people_type=people_type)
        obj.state = 'draft'
        obj.save()
        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class DimissionDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get("id", None)
        obj = Dimission.objects.get(id=id)
        audit_dic, flow_dict, five_node_list = {}, {}, []
        for audit_obj in obj.dimissionauditrecord_set.all():
            if audit_obj.node == 'five' and audit_obj.node_name not in five_node_list:
                five_node_list.append(audit_obj.node_name)
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, "node_name": audit_obj.node_name, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.dimissionauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, "node_name": audit_obj.node_name, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"), 'file_type': atta_obj.file_type,
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        Rsk_obj = Company.objects.get(id=16).head_people
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list, 'five_node_list': five_node_list,
                   'is_edit': 'true' if obj.state == 'refuse' and obj.user == request.user else 'false',
                   'is_audit': 'true' if obj.state in ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] and request.user == Rsk_obj else 'false',
                   "is_flag": 'true' if obj.group_grade in ['F1', 'F2', 'F3'] else 'false', "flow_dict": flow_dict,
                   "file_path": Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/dimission_detail_view.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        obj = Dimission.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)

        obj.current_audit_users.remove(request.user)

        if obj.state == 'zero':
            audit_record = obj.dimissionauditrecord_set.filter(node='zero', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.dimissionauditrecord_set.filter(node='one'):
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='one', state='unaudit')
                    obj_state = 'one'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                elif obj.dimissionauditrecord_set.filter(node='two'):
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='two', state='unaudit')
                    obj_state = 'two'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                elif obj.dimissionauditrecord_set.filter(node='three'):
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='three', state='unaudit')
                    obj_state = 'three'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                elif obj.dimissionauditrecord_set.filter(node='four'):
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='four', state='unaudit')
                    obj_state = 'four'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                else:
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='five', state='unaudit')
                    obj_state = 'five'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.user)

        elif obj.state == 'one':
            audit_record = obj.dimissionauditrecord_set.filter(node='one', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.dimissionauditrecord_set.filter(node='two'):
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='two', state='unaudit')
                    obj_state = 'two'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                elif obj.dimissionauditrecord_set.filter(node='three'):
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='three', state='unaudit')
                    obj_state = 'three'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                elif obj.dimissionauditrecord_set.filter(node='four'):
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='four', state='unaudit')
                    obj_state = 'four'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                else:
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='five', state='unaudit')
                    obj_state = 'five'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.user)

        elif obj.state == 'two':
            audit_record = obj.dimissionauditrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.dimissionauditrecord_set.filter(node='three'):
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='three', state='unaudit')
                    obj_state = 'three'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                elif obj.dimissionauditrecord_set.filter(node='four'):
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='four', state='unaudit')
                    obj_state = 'four'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                else:
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='five', state='unaudit')
                    obj_state = 'five'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.user)

        elif obj.state == 'three':
            audit_record = obj.dimissionauditrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.dimissionauditrecord_set.filter(node='four'):
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='four', state='unaudit')
                    obj_state = 'four'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
                else:
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='five', state='unaudit')
                    obj_state = 'five'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.user)

        elif obj.state == 'four':
            audit_record = obj.dimissionauditrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_record = obj.dimissionauditrecord_set.filter(node='five', state='unaudit')
                obj_state = 'five'
                for next_audit in next_audit_record:
                    obj.current_audit_users.add(next_audit.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.user)

        elif obj.state == 'five':
            audit_record = obj.dimissionauditrecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.dimissionauditrecord_set.filter(node='five', state='unaudit', audit_people=request.user).count() > 1:
                    obj.current_audit_users.add(request.user)
                if obj.current_audit_users.all().count():
                    obj_state = 'five'
                else:
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='six', state='unaudit')
                    obj_state = 'six'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.user)

        elif obj.state == 'six':
            audit_record = obj.dimissionauditrecord_set.filter(node='six', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.current_audit_users.all().count():
                    obj_state = 'six'
                else:
                    next_audit_record = obj.dimissionauditrecord_set.filter(node='seven', state='unaudit')
                    obj_state = 'seven'
                    for next_audit in next_audit_record:
                        obj.current_audit_users.add(next_audit.audit_people)
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.user)

        elif obj.state == 'seven':
            audit_record = obj.dimissionauditrecord_set.filter(node='seven', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                if obj.current_audit_users.all().count():
                    obj_state = 'seven'
                else:
                    obj_state = 'end'
            else:
                obj_state = 'refuse'
                obj.current_audit_users.clear()
                obj.current_audit_users.add(obj.user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if obj_state == 'refuse':
            obj.before_status = obj.state
            obj.returned_person = request.user

        obj.state = obj_state
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class DimissionApplyWriteView(View):
    def post(self, request):
        id = request.POST.get('flow_id', '')
        obj = Dimission.objects.get(id=int(id))
        if obj.state != 'refuse':
            returnData = {'code': 500, 'message': '只有拒绝状态才能修改！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        hiredate = request.POST.get('hiredate', None)   # 入职时间
        dimission_time = request.POST.get('dimission_time', None)   # 离职时间
        dimission_note = request.POST.get('dimission_note', None)   # 离职原因

        obj.hiredate = hiredate
        obj.dimission_time = dimission_time
        obj.dimission_note = dimission_note
        obj.current_audit_users.clear()

        obj.state = obj.before_status
        RecordObjs = obj.dimissionauditrecord_set.filter(node=obj.before_status, state='unaudit')
        for i in RecordObjs:
            obj.current_audit_users.add(i.audit_people)
        obj.current_audit_users.add(obj.returned_person)

        before_obj = obj.dimissionauditrecord_set.filter(node=obj.before_status, audit_people=obj.returned_person).first()
        DimissionAuditRecord.objects.create(parent_id=obj, state='unaudit', node=obj.before_status, audit_people=obj.returned_person, audit_note='', node_name=before_obj.node_name)
        obj.save()
        returnData = {'code': 200, 'message': '修改成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class DimissionApplyRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = Dimission.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的请假申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.dimissionauditrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的请假申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的请假申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                discontinue_reason = request.POST.get('discontinue_reason', '')       # 中止原因
                file_lenth = request.POST.get('file_lenth', '')
                fj_number = request.POST.get('fj_number', '')
                for i in range(int(file_lenth)):
                    files = request.FILES.get(f'file{i}')
                    file_obj = Topicsattachments.objects.create(
                        topics_number=fj_number, file_size=public_file.StrOfSize(files.size), file_path=files, uploader=request.user.username,
                        uploader_user=request.user, file_type=1, is_deleted=False, source='LZSQ'
                    )
                    sys_path = os.getcwd()
                    file_name = files.name
                    file_obj.file_name = file_name
                    file_obj.save()

                    word_path = sys_path + '/media/' + str(file_obj.file_path)
                    old_word_path = word_path
                    temp_name = os.path.splitext(file_name)[0]
                    new_word_path = old_word_path.replace(os.path.splitext(file_obj.file_path.name.split("/")[-1])[0], temp_name)
                    os.rename(old_word_path, new_word_path)
                    word_path = new_word_path

                    file_path = file_obj.file_path.name.replace(os.path.splitext(file_obj.file_path.name.split("/")[-1])[0], temp_name)

                    pdf_path = word_path
                    if word_path.split('.')[-1] in ['docx', 'doc', 'DOC', 'DOCX']:
                        pdf_path = ParseWord().word2pdf(word_path)
                    elif word_path.split(".")[-1] in ['ppt', 'pptx']:
                        pdf_path = ParseWord().ppt2pdf(word_path)
                    elif word_path.split(".")[-1] in ['xls', 'xlsx', 'XLS', 'XLSX']:
                        b = xlrd.open_workbook(word_path)
                        sheetnum = len(b.sheets())
                        pdfConverter = PDFConverter(word_path, sheetnum, os.path.splitext(file_name)[0])
                        pdf_path = pdfConverter.run_conver()
                    else:
                        pdf_path = '/media/' + str(file_path)
                    pdf_list = []
                    if type(pdf_path) is list:
                        for i in range(len(pdf_path)):
                            if i == 0:
                                file_obj.pdf_path = pdf_path[i].replace(os.getcwd(), '')
                                tic_id = file_obj.id
                                file_obj.save()
                            else:
                                all_file = Topicsattachments.objects.create(
                                    topics_number=fj_number, file_path=files, file_size=public_file.StrOfSize(files.size), uploader=request.user.username, file_type=1,
                                    pdf_path=pdf_path[i].replace(os.getcwd(), ''), file_name=os.path.split(pdf_path[i])[1], source="LZSQ", uploader_user=request.user.username
                                )
                                tic_id = all_file.id
                            one_dict = {"id": tic_id, 'pdf_path': pdf_path[i].replace(os.getcwd(), '')}
                            pdf_list.append(one_dict)
                    else:
                        fileName = pdf_path.split("/")[-1].split(".")[0]
                        pdf_path = pdf_path.replace(fileName, files.name.split(".")[0]).replace(os.getcwd(), "")
                        pdf_path = pdf_path.replace(os.path.splitext(os.path.split(pdf_path)[1])[0], os.path.splitext(file_name)[0])
                        file_obj.pdf_path = pdf_path
                        file_obj.save()
                DimissionAuditRecord.objects.create(parent_id=obj, state='audit', node='stop', audit_people=request.user, audit_note=discontinue_reason)
                obj.dimissionauditrecord_set.filter(state='unaudit').delete()
                obj.audit_users_already.add(request.user)
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 中层干部外出
class middle_level_cadres(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "table_name": "finance_outgoingcadresdata"}
        return render(request, 'finance/OutgoingCadresList.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = OutgoingCadresData.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), apply_user=request.user).order_by('-create_time')

        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'outgoing_person': ", ".join([i.real_name for i in obj.outgoing_person.all()]),
                      'start_time': obj.start_time, 'end_time': obj.end_time, 'title': obj.title,
                      'company': obj.company.name, 'state': obj.get_state_str(), 'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
                      'url': f"<a href='middle_level_draft.html?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>" if obj.get_state_str() == '草稿'
                      else (f"<a href='middle_level_detail.html?id={obj.id}'>查看</a> | <a href='middle_level_detail.html?revise=true&id={obj.id}'>修改</a>"
                            if (obj.can_revise == '1' and obj.state in ['one', 'nine', 'two', 'three'])
                            else (
                          f"<a href='middle_level_detail.html?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                          if obj.state == 'stop' else f"<a href='middle_level_detail.html?id={obj.id}'>查看</a>"))}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 中层干部外出审批申请
class OutgoingCadres(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        dzb_obj = Company.objects.get(id=3).head_people
        PartyGovOffice = 'false' if request.user == dzb_obj else "true"

        is_functional = "true" if request.user.company.is_functional else "false"
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'uuid': uuid.uuid1(), "PartyGovOffice": PartyGovOffice, "is_functional": is_functional}
        return render(request, 'finance/OutgoingCadres.html', context)

    def post(self, request):
        user = request.user
        uuid = request.POST.get('uuid', None)
        outgoing_id = request.POST.get('id', None)
        outgoing_person = request.POST.get('outgoing_person', None)                    # 外出人员
        duties = request.POST.get('duties', None)                             # 职务
        start_time = request.POST.get('start_time', None)                         # 开始时间
        end_time = request.POST.get('end_time', None)                           # 结束时间
        destination = request.POST.get('destination', None)                        # 前往地点
        reasons = request.POST.get('reasons', None)                            # 外出事由
        department_list = json.loads(request.POST.get('department_list', None))                    # 分管科室
        revise = request.POST.get('revise', None)               # 是否自己修改
        outgoing_person_list = re.findall('\((.*?)\)', outgoing_person)
        outgoing_person_obj = User.objects.filter(job_number__in=outgoing_person_list)
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "中层干部外出")
        except:
            pass
        if outgoing_id:
            obj = OutgoingCadresData.objects.get(id=int(outgoing_id))
            obj.title = reasons
            obj.start_time = start_time
            obj.end_time = end_time
            obj.duties = duties
            obj.destination = destination
            obj.state = 'one'
            obj.current_audit_users.clear()
            if revise.strip():
                print("删除全部")
                obj.outgoingcadresdatarecord_set.all().delete()
            else:
                print("删除未审批")
                obj.outgoingcadresdatarecord_set.filter(state='unaudit').delete()
        else:
            obj = OutgoingCadresData.objects.create(
                uuid=uuid, title=reasons, start_time=start_time, end_time=end_time, duties=duties, destination=destination, state='one',
                apply_user=user, company=user.company
            )
        # 添加出行人员
        for i in outgoing_person_obj:
            obj.outgoing_person.add(i)

        # 添加分管部门
        flag = True
        for t in department_list:
            company_obj = Company.objects.get(id=int(t))
            obj.department_charge=company_obj
            one_step = company_obj.head_people
            OutgoingCadresDataRecord.objects.create(node='one', parent_id=obj, audit_people=one_step)
            obj.current_audit_users.add(one_step)
            flag = False

        #分管领导
        OutgoingCadresDataRecord.objects.create(node='two', parent_id=obj, audit_people=user.company.leaders_id)
        if flag:
            obj.current_audit_users.add(user.company.leaders_id)
            obj.state = 'two'

        # 党政办审核
        four_prave = Company.objects.get(id=3).head_people
        OutgoingCadresDataRecord.objects.create(node='four', parent_id=obj, audit_people=four_prave)

        # 党政办接收
        OutgoingCadresDataRecord.objects.create(node='three', parent_id=obj, audit_people=Staffing.objects.get(station='外出干部审核员').post_personnel.all().first())
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "干部外出"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'message': '创建成功！', "code": 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 中层干部外出审批详情页
class middle_level_detail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        outgoing_id = request.GET.get("id", None)
        revise = request.GET.get("revise", '')
        outgoing_obj = OutgoingCadresData.objects.get(id=int(outgoing_id))
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=outgoing_obj.uuid)]

        audit_dic, flow_dict = {}, {}
        for audit_obj in outgoing_obj.outgoingcadresdatarecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in outgoing_obj.outgoingcadresdatarecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   'apply': outgoing_obj.apply_user.real_name,
                   "company": outgoing_obj.company.name, 'uuid': outgoing_obj.uuid, 'file_list': file_list,
                   'obj': outgoing_obj, "audit_dic": audit_dic,
                   "is_audit": "true" if outgoing_obj.state in ['one', 'two', 'three', 'four'] and request.user in outgoing_obj.current_audit_users.all() else 'false',
                   "is_edit": "true" if (outgoing_obj.state == 'eight' and request.user == outgoing_obj.apply_user) or revise else 'false',
                   "is_stop": "true" if outgoing_obj.state in ['one', 'two', 'three', 'four', 'eight'] and request.user == outgoing_obj.apply_user else 'false',
                   "flow_dict": flow_dict, "revise": revise,
                   "file_path": Topicsattachments.objects.filter(topics_number=outgoing_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=outgoing_obj.uuid) else ""}
        return render(request, 'finance/middle_level_detail.html', context)

    def post(self, request):
        outgoing_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "中层干部外出")
        except:
            pass
        outgoing_obj = OutgoingCadresData.objects.get(id=int(outgoing_id))

        if not outgoing_obj.outgoingcadresdatarecord_set.filter(node=outgoing_obj.state, state='unaudit', audit_people=request.user).count():
            returnData = {'code': 500, 'message': '该流程已审核，无需重复点击！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

        if outgoing_obj.state == 'one':
            audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='one', state='unaudit').first()
            next_audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='two', state='unaudit').first()
            outgoing_obj.current_audit_users.clear()
            if state == 'audit':
                obj_state = 'two'
                outgoing_obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                outgoing_obj.current_audit_users.add(outgoing_obj.apply_user)
            audit_record.update_time = datetime.now()
            audit_record.state = state
            audit_record.audit_note = audit_note
            audit_record.save()
        elif outgoing_obj.state == 'two':
            audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='two', state='unaudit').first()
            outgoing_obj.current_audit_users.clear()
            if state == 'audit':
                four_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='four', state='unaudit')
                if four_record:
                    this_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='four', state='unaudit').first()
                    one_node = outgoing_obj.outgoingcadresdatarecord_set.filter(node='one', audit_people=this_record.audit_people)
                    if one_node:
                        this_record.update_time = datetime.now()
                        this_record.state = one_node.last().state
                        this_record.audit_note = one_node.last().audit_note
                        this_record.save()
                        next_audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='three', state='unaudit').first()
                        this_status = 'three'
                    else:
                        next_audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='four', state='unaudit').first()
                        this_status = 'four'
                else:
                    next_audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='three', state='unaudit').first()
                    this_status = 'three'
                obj_state = this_status
                outgoing_obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                outgoing_obj.current_audit_users.add(outgoing_obj.apply_user)
            audit_record.update_time = datetime.now()
            audit_record.state = state
            audit_record.audit_note = audit_note
            audit_record.save()

        elif outgoing_obj.state == 'four':
            audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='four', state='unaudit').first()
            next_audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='three', state='unaudit').first()
            outgoing_obj.current_audit_users.clear()
            if state == 'audit':
                obj_state = 'three'
                outgoing_obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                outgoing_obj.current_audit_users.add(outgoing_obj.apply_user)
            audit_record.update_time = datetime.now()
            audit_record.state = state
            audit_record.audit_note = audit_note
            audit_record.save()

        else:
            audit_record = outgoing_obj.outgoingcadresdatarecord_set.filter(node='three', state='unaudit').first()
            outgoing_obj.current_audit_users.clear()
            if state == 'audit':
                obj_state = 'seven'
                MakeCopy.objects.create(recipient=Company.objects.get(id=16).head_people, process_id=outgoing_obj.id, type='n')
            else:
                obj_state = 'eight'
                outgoing_obj.current_audit_users.add(outgoing_obj.apply_user)
            audit_record.update_time = datetime.now()
            audit_record.state = state
            audit_record.audit_note = audit_note
            audit_record.save()
        outgoing_obj.audit_users_already.add(request.user)
        outgoing_obj.state = obj_state
        outgoing_obj.can_revise = "0"
        outgoing_obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "干部外出"
        applicant = outgoing_obj.apply_user.real_name
        ApplicationTime = outgoing_obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = outgoing_obj.title[:15] + "……" if len(outgoing_obj.title) > 15 else outgoing_obj.title
        for jj in outgoing_obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class middle_level_draft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        outgoing_id = request.GET.get("id", None)
        outgoing_obj = OutgoingCadresData.objects.get(id=int(outgoing_id))
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=outgoing_obj.uuid)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'file_list': file_list, 'obj': outgoing_obj}
        return render(request, 'finance/middle_level_draft.html', context)

    def post(self, request):
        user = request.user
        uuid = request.POST.get('uuid', None)
        outgoing_id = request.POST.get('id', None)
        outgoing_person = request.POST.get('outgoing_person', None)                    # 外出人员
        duties = request.POST.get('duties', None)                             # 职务
        start_time = request.POST.get('start_time', None)                         # 开始时间
        end_time = request.POST.get('end_time', None)                           # 结束时间
        destination = request.POST.get('destination', None)                        # 前往地点
        reasons = request.POST.get('reasons', None)                            # 外出事由
        department_list = json.loads(request.POST.get('department_list', None))                    # 分管科室
        outgoing_person_list = re.findall('\((.*?)\)', outgoing_person)
        outgoing_person_obj = User.objects.filter(job_number__in=outgoing_person_list)

        if outgoing_id:
            obj = OutgoingCadresData.objects.get(id=int(outgoing_id))
            obj.title = reasons
            obj.start_time = start_time
            obj.end_time = end_time
            obj.duties = duties
            obj.destination = destination
        else:
            obj = OutgoingCadresData.objects.create(
                uuid=uuid, title=reasons, start_time=start_time, end_time=end_time, duties=duties, destination=destination, state='draft',
                apply_user=user, company=user.company
            )
        # 添加出行人员
        for i in outgoing_person_obj:
            obj.outgoing_person.add(i)

        # 添加分管部门
        for t in department_list:
            company_obj = Company.objects.get(id=int(t))
            obj.department_charge = company_obj

        obj.save()
        returnDict = {'message': '保存成功！', "code": 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class middle_level_revoke(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = OutgoingCadresData.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的请假申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.outgoingcadresdatarecord_set_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的请假申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的请假申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


# 工会经费申请列表
class labor_union_expenses(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'table_name': "finance_laborunionexpenses"}
        return render(request, 'finance/labor_union_expenses.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", '')
        objs = LaborUnionExpenses.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(company__name__contains=search_value), apply_user=request.user).order_by('-create_time')
        # 'one', 'two', 'three', 'four', 'five', 'six', 'nine'
        data_list = [
            {'id': obj.id, 'apply_user': obj.apply_user.real_name, 'payee': obj.payee, 'total_money': obj.total_money, 'pay_reason': obj.pay_reason,
                      'state': obj.get_str_state(), 'current_audit_users': ', '.join([i.real_name for i in obj.current_audit_users.all()]),
                      'url': f"<a href='LaborUnionExpensesdraft.html?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                      if obj.get_str_state() == '草稿' else (f"<a href='LaborUnionExpensesdetail.html?id={obj.id}'>查看</a> | <a href='LaborUnionExpensesdetail.html?revise=true&id={obj.id}'>修改</a>"
                                                           if (obj.can_revise == '1' and obj.state not in ['draft', 'stop']) else (f"<a href='LaborUnionExpensesdetail.html?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"
                                                                                                                                   if obj.state == 'stop' else f"<a href='LaborUnionExpensesdetail.html?id={obj.id}'>查看</a>"))}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 工会经费申请列表
class LaborUnionExpensesIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'uuid': uuid.uuid1()}
        return render(request, 'finance/labor_union_expenses_index.html', context)

    def post(self, request):
        # apply_user = request.user
        # company = request.user.company
        # logis_id = request.POST.get('id', None)
        # daxie = request.POST.get('daxie', None)  # 大写
        # total_money = request.POST.get('total_money', 0)  # 总金额
        # fj_number = request.POST.get('uuid', None)
        # rask = request.POST.get('rask', None)  # 备注
        # payee = request.POST.get('payee', None)  # 收款单位
        # payee_account = request.POST.get('payee_account', None)  # 收款账号
        # pay_type = request.POST.get('pay_type', None)  # 付款类型
        # pay_reason = request.POST.get('pay_reason', None)  # 付款事由
        # check_or_not = request.POST.get('check_or_not', None)  # 是否会计核对
        # BankDeposit = request.POST.get('BankDeposit', None)  # 开户行
        # admin_flag = request.POST.get('admin', None)
        # # ************************************************ 保存操作记录 ************************************
        # try:
        #     RecordAndPush().OperationRecords(request, "工会经费")
        # except:
        #     pass
        # if logis_id:
        #     obj = LaborUnionExpenses.objects.get(id=int(logis_id))
        #     obj.payee_account = payee_account
        #     obj.BankDeposit = BankDeposit
        #     obj.total_money = total_money
        #     obj.pay_reason = pay_reason
        #     obj.fj_number = fj_number
        #     obj.pay_type = pay_type
        #     obj.daxie = daxie
        #     obj.payee = payee
        #     obj.rask = rask
        #     obj.save()
        #     if not admin_flag:
        #         obj.current_audit_users.clear()
        #         obj.laborunionexpensesrecord_set.filter(state='unaudit').delete()
        #     message = '修改成功！'
        # else:
        #     obj = LaborUnionExpenses.objects.create(apply_user=apply_user, payee_account=payee_account, BankDeposit=BankDeposit, total_money=total_money,
        #                                          pay_reason=pay_reason, fj_number=fj_number, company=company, pay_type=pay_type, daxie=daxie, payee=payee, rask=rask)
        #     message = '创建成功！'
        # if not admin_flag:
        #     flag, flag1, flag2 = True, True, True
        #     one_step = company.head_people
        #     if apply_user != one_step:
        #         LaborUnionExpensesRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=obj)
        #         obj.state = 'one'
        #         obj.current_audit_users.add(one_step)
        #         flag = False
        #     if pay_type == '1':
        #         if check_or_not == '1':
        #             flag1 = False
        #             htkj_obj = Staffing.objects.get(station='工会经费审核会计').post_personnel.all()
        #             for htkj in htkj_obj:
        #                 LaborUnionExpensesRecord.objects.create(node='two', audit_note='', audit_people=htkj, parent_id=obj)
        #                 if flag:
        #                     obj.state = 'two'
        #                     obj.current_audit_users.add(htkj)
        #         three_setp = Company.objects.get(id=22).head_people
        #         LaborUnionExpensesRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=obj)
        #         if flag and flag1:
        #             obj.state = 'three'
        #             obj.current_audit_users.add(three_setp)
        #             flag2 = False
        #
        #     four_step = Company.objects.get(id=23).head_people
        #     LaborUnionExpensesRecord.objects.create(node='four', audit_note='', audit_people=four_step, parent_id=obj)
        #     if flag and flag1 and flag2:
        #         obj.state = 'four'
        #         obj.current_audit_users.add(four_step)
        #
        #     LaborUnionExpensesRecord.objects.create(node='five', audit_note='', audit_people=company.leaders_id, parent_id=obj)
        #
        #     if float(total_money.replace(",", "")) < 10000:
        #         LaborUnionExpensesRecord.objects.create(node='six', state='unaudit',
        #                                                   audit_people=Staffing.objects.get(station='工会主席').post_personnel.all().first(), parent_id=obj)
        #     elif 1000 <= float(total_money.replace(",", "")) < 200000:
        #         LaborUnionExpensesRecord.objects.create(node='six', state='unaudit',
        #                                                   audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=obj)
        #     else:
        #         LaborUnionExpensesRecord.objects.create(node='six', state='unaudit',
        #                                                   audit_people=Staffing.objects.get(station='书记').post_personnel.all().first(), parent_id=obj)
        #
        #     LaborUnionExpensesRecord.objects.create(node='nine', audit_note='', audit_people=Staffing.objects.get(station='财务出纳').post_personnel.all().first(), parent_id=obj)
        #     obj.save()
        #     # ********************************************** 发送小程序推送 ******************************************
        #     topic_type = "工会经费"
        #     applicant = obj.apply_user.real_name
        #     ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        #     SubjectMatter = obj.pay_reason[:15] + "……" if len(obj.pay_reason) > 15 else obj.pay_reason
        #     for jj in obj.current_audit_users.all():
        #         try:
        #             RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        #         except:
        #             pass
        # returnDict = {'status': 'success', 'message': message, 'code': 200}
        # return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'status': 'success', 'message': "该流程已关闭，现已无法申请！", 'code': 400}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 工会经费详情&审批
class LaborUnionExpensesdetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = LaborUnionExpenses.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.laborunionexpensesrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.laborunionexpensesrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six", "nine"] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', "nine"] and request.user == obj.apply_user else 'false',
                   'uuid': uuid.uuid1(), 'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/LaborUnionExpensesdetail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "工会经费")
        except:
            pass
        obj = LaborUnionExpenses.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.laborunionexpensesrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                if obj.laborunionexpensesrecord_set.filter(node='two'):
                    next_audit_record_list = obj.laborunionexpensesrecord_set.filter(node='two', state='unaudit')
                    obj_state = 'two'
                    for next in next_audit_record_list:
                        next.state = 'audit'
                        next.save()
                        obj.current_audit_users.add(next.audit_people)
                elif obj.laborunionexpensesrecord_set.filter(node='three'):
                    next_audit_record = obj.laborunionexpensesrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    next_audit_record = obj.laborunionexpensesrecord_set.filter(node='four', state='unaudit').first()
                    obj_state = 'four'
                    obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = None
            if state == 'audit':
                audit_list = obj.laborunionexpensesrecord_set.filter(node='two', state='unaudit')
                for zero in audit_list:
                    if request.user == zero.audit_people:
                        audit_record = zero
                next_audit_record = obj.laborunionexpensesrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.laborunionexpensesrecord_set.filter(node='three', state='unaudit').first()
            next_audit_record = obj.laborunionexpensesrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.laborunionexpensesrecord_set.filter(node='four', state='unaudit').first()
            next_audit_record = obj.laborunionexpensesrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.laborunionexpensesrecord_set.filter(node='five', state='unaudit').first()
            next_audit_record = obj.laborunionexpensesrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = 'six'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.laborunionexpensesrecord_set.filter(node='six', state='unaudit').first()
            next_audit_record = obj.laborunionexpensesrecord_set.filter(node='nine', state='unaudit').first()
            if state == 'audit':
                obj_state = 'nine'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'nine':
            audit_record = obj.laborunionexpensesrecord_set.filter(node='nine', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "工会经费"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.pay_reason[:15] + "……" if len(obj.pay_reason) > 15 else obj.pay_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 工会经费草稿
class LaborUnionExpensesdraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        obj = LaborUnionExpenses.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.laborunionexpensesrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.laborunionexpensesrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'uuid': uuid.uuid1(), 'flow_dict': flow_dict,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace(
                       "\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/labor_union_draft.html', context)

    def post(self, request):
        # apply_user = request.user
        # company = request.user.company
        # logis_id = request.POST.get('id', None)
        # daxie = request.POST.get('daxie', None)  # 大写
        # total_money = request.POST.get('total_money', 0)  # 总金额
        # fj_number = request.POST.get('uuid', None)
        # rask = request.POST.get('rask', None)  # 备注
        # payee = request.POST.get('payee', None)  # 收款单位
        # payee_account = request.POST.get('payee_account', None)  # 收款账号
        # pay_type = request.POST.get('pay_type', None)  # 付款类型
        # pay_reason = request.POST.get('pay_reason', None)  # 付款事由
        # BankDeposit = request.POST.get('BankDeposit', None)  # 开户行
        # if logis_id:
        #     obj = LaborUnionExpenses.objects.get(id=int(logis_id))
        #     obj.payee_account = payee_account
        #     obj.BankDeposit = BankDeposit
        #     obj.total_money = total_money
        #     obj.pay_reason = pay_reason
        #     obj.fj_number = fj_number
        #     obj.pay_type = pay_type
        #     obj.daxie = daxie
        #     obj.payee = payee
        #     obj.rask = rask
        #     obj.state = 'draft'
        #     obj.save()
        # else:
        #     obj = LaborUnionExpenses.objects.create(apply_user=apply_user, payee_account=payee_account,
        #                                             BankDeposit=BankDeposit, total_money=total_money,
        #                                             pay_reason=pay_reason, fj_number=fj_number, company=company,
        #                                             pay_type=pay_type, daxie=daxie, payee=payee, rask=rask, state='draft')
        #
        # returnDict = {'code': 200, 'message': '保存成功！'}
        # return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'status': 'success', 'message': "该流程已关闭，现已无法保存！", 'code': 400}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 工会经费流程中止
class LaborUnionExpensesstop(View):
    def post(self, request):
        sub_id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        obj = LaborUnionExpenses.objects.get(id=int(sub_id))
        obj.state = state
        obj.current_audit_users.clear()
        obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 学科经费申请列表
class subject_funding_list(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "table_name": "finance_subjectfunding"}
        return render(request, 'finance/subject_funding_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.subjectfunding_set.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'pay_reason': obj.pay_reason,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='subject_funding_darf.html?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>" if obj.state == 'draft' else (
                          f"<a href='subject_funding_detail.html?id={obj.id}'>查看</a> | <a href='subject_funding_detail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state in [
                              'one', 'two', 'three'] else (f"<a href='subject_funding_detail.html?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"if obj.state == 'stop' else f"<a href='subject_funding_detail.html?id={obj.id}'>查看</a>")),
                      'state': obj.get_str_state(),
                      'total_money': obj.total_money}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class subject_funding_index(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'uuid': uuid.uuid1()}
        return render(request, 'finance/subject_funding_index.html', context)

    def post(self, request):
        # apply_user = request.user
        # company = request.user.company
        # Subject_id = request.POST.get('id', None)
        # pay_reason = request.POST.get("pay_reason", "")
        # rask = request.POST.get("rask", "")
        # total_money = request.POST.get("total_money", "")
        # daxie = request.POST.get("daxie", "")
        # back = request.POST.get("back", "")
        # people_type = request.POST.get("people_type", "")
        # pay_detail = request.POST.get("pay_detail", "")
        # fj_number = request.POST.get("fj_number", "")
        # admin_flag = request.POST.get("admin", "")
        # payee = request.POST.get("payee", "")
        # account_number = request.POST.get("account_number", "")
        # # ************************************************ 保存操作记录 ************************************
        # try:
        #     RecordAndPush().OperationRecords(request, "学科经费")
        # except:
        #     pass
        # try:
        #     float(total_money.replace(",", ""))
        # except Exception as E:
        #     print("===================", E)
        #     returnDict = {'code': 400, 'message': '总金额需为数字！'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        #
        # if Subject_id:
        #     obj = SubjectFunding.objects.get(id=int(Subject_id))
        #     obj.pay_reason = pay_reason
        #     obj.total_money = total_money
        #     obj.fj_number = fj_number
        #     obj.payee = payee
        #     obj.account_number = account_number
        #     obj.pay_detail = pay_detail
        #     obj.people_type = people_type
        #     obj.daxie = daxie
        #     obj.rask = rask
        #     if back:
        #         obj.subjectfundingrecord_set.filter(state='unaudit').delete()
        #         obj.current_audit_users.clear()
        # else:
        #     obj = SubjectFunding.objects.create(apply_user=apply_user, company=company, pay_detail=pay_detail, total_money=total_money, payee=payee, account_number=account_number,
        #                                             pay_reason=pay_reason, fj_number=fj_number, daxie=daxie, rask=rask, people_type=people_type)
        # if not admin_flag:
        #     one_step = company.head_people
        #     flag = True
        #     if apply_user != one_step:
        #         SubjectFundingRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=obj)
        #         obj.state = 'one'
        #         obj.current_audit_users.add(one_step)
        #         flag = False
        #
        #     two_setp = Company.objects.get(id=14).head_people
        #     SubjectFundingRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=obj)
        #     if flag:
        #         obj.state = 'two'
        #         obj.current_audit_users.add(two_setp)
        #
        #     three_setp = Company.objects.get(id=14).leaders_id
        #     SubjectFundingRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=obj)
        #
        #     four_setp = Company.objects.get(id=23).head_people
        #     SubjectFundingRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=obj)
        #
        #     five_setp = Staffing.objects.get(station='工会主席').post_personnel.all().first() if float(total_money.replace(",", "")) <= 10000 else Staffing.objects.get(station='院长').post_personnel.all().first() if 10000 < float(total_money.replace(",", "")) <= 200000 else Staffing.objects.get(station='书记').post_personnel.all().first()
        #     SubjectFundingRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=obj)
        #
        #     six_setp = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        #     SubjectFundingRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=obj)
        #     # ********************************************** 发送小程序推送 ******************************************
        #     topic_type = "餐补付款"
        #     applicant = obj.apply_user.real_name
        #     ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        #     SubjectMatter = obj.pay_reason[:15] + "……" if len(obj.pay_reason) > 15 else obj.pay_reason
        #     for jj in obj.current_audit_users.all():
        #         try:
        #             RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        #         except:
        #             pass
        # obj.save()
        # returnDict = {'status': 'success', 'message': "", 'code': 200}
        returnDict = {'status': 'success', 'message': "该流程已关闭，现已无法申请！", 'code': 400}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 学科经费申请详情&审批
class subject_funding_detail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = SubjectFunding.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.subjectfundingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.subjectfundingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false',
                   'flow_dict': flow_dict, "revise": revise, "pay_detail": json.loads(obj.pay_detail),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace( "\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/subject_funding_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "学科经费")
        except:
            pass
        obj = SubjectFunding.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.subjectfundingrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.subjectfundingrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.subjectfundingrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.subjectfundingrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.subjectfundingrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.subjectfundingrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.subjectfundingrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.subjectfundingrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.subjectfundingrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                if obj.subjectfundingrecord_set.filter(node='six'):
                    next_audit_record = obj.subjectfundingrecord_set.filter(node='six', state='unaudit').first()
                    obj_state = 'six'
                    obj.current_audit_users.add(next_audit_record.audit_people)
                else:
                    obj_state = 'seven'
                    if obj.people_type == "1":
                        try:
                            headers = {
                                "Content-Type": 'application/json'
                            }
                            for rson in json.loads(obj.pay_detail):
                                post_data = {
                                    'key': 'hOJYdf7WoMTZV06Q',
                                    'department_name': obj.company.name,
                                    'time': obj.create_time.strftime("%Y-%m-%d"),
                                    'amount': float(rson['budget_amount'].replace(",", ''))/10000,
                                    'agent_name': obj.apply_user.real_name,
                                    'reason': rson['goods_name']
                                }
                                req = requests.post(url=post_url, headers=headers, data=json.dumps(post_data))
                                print(req.text)
                        except:
                            print("同步更新出错")
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.subjectfundingrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
                if obj.people_type == "1":
                    try:
                        headers = {
                            "Content-Type": 'application/json'
                        }
                        for rson in json.loads(obj.pay_detail):
                            post_data = {
                                'key': 'hOJYdf7WoMTZV06Q',
                                'department_name': obj.company.name,
                                'time': obj.create_time.strftime("%Y-%m-%d"),
                                'amount': float(rson['budget_amount'].replace(",", ''))/10000,
                                'agent_name': obj.apply_user.real_name,
                                'reason': rson['goods_name']
                            }
                            req = requests.post(url=post_url, headers=headers, data=json.dumps(post_data))
                            print(req.text)
                    except:
                        print("同步更新出错")
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "学科经费"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.pay_reason[:15] + "……" if len(obj.pay_reason) > 15 else obj.pay_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 学科经费草稿
class subject_funding_darf(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = SubjectFunding.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.subjectfundingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.subjectfundingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'flow_dict': flow_dict, "revise": revise, "pay_detail": json.loads(obj.pay_detail),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace( "\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/subject_funding_darf.html', context)

    def post(self, request):
        apply_user = request.user
        company = request.user.company
        Subject_id = request.POST.get('id', None)
        pay_reason = request.POST.get("pay_reason", "")
        pay_type = request.POST.get("pay_type", "")
        rask = request.POST.get("rask", "")
        people_type = request.POST.get("people_type", "")
        total_money = request.POST.get("total_money", "")
        daxie = request.POST.get("daxie", "")
        pay_detail = request.POST.get("pay_detail", "")
        fj_number = request.POST.get("fj_number", "")
        revise = request.POST.get("revise", "")
        payee = request.POST.get("payee", "")
        account_number = request.POST.get("account_number", "")
        if Subject_id:
            obj = SubjectFunding.objects.get(id=int(Subject_id))
            obj.pay_reason = pay_reason
            obj.total_money = total_money
            obj.people_type = people_type
            obj.pay_type = pay_type
            obj.pay_detail = pay_detail
            obj.daxie = daxie
            obj.rask = rask
            obj.payee = payee
            obj.account_number = account_number
            if not revise:
                obj.state = "draft"
            obj.save()
        else:
            obj = SubjectFunding.objects.create(apply_user=apply_user, company=company, pay_type=pay_type, pay_detail=pay_detail, total_money=total_money, payee=payee, account_number=account_number,
                                                    pay_reason=pay_reason, fj_number=fj_number, daxie=daxie, rask=rask, state="draft", people_type=people_type)
        returnDict = {'status': 'success', 'message': "", 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 学科经费中止
class subject_funding_stop(View):
    def post(self, request):
        sub_id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        obj = SubjectFunding.objects.get(id=int(sub_id))
        obj.state = state
        obj.current_audit_users.clear()
        obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class SealMakingApplyView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "apply_time": datetime.now(), "uuid": uuid.uuid1()}
        return render(request, 'finance/seal_making_apply_view.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        apply_user = request.user
        company = request.user.company
        seal_name = request.POST.get("seal_name", None)
        making_number = request.POST.get("making_number", None)
        reason = request.POST.get("reason", None)
        fj_number = request.POST.get('uuid', None)
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "印章刻制")
        except:
            pass
        if id:
            obj = SealMaking.objects.get(id=int(id))
            obj.apply_user = apply_user
            obj.company = company
            obj.making_number = making_number
            obj.plan_seal_name = seal_name
            obj.reason = reason
            obj.fj_number = fj_number
            obj.state = "one"
            obj.can_revise = "1"
            obj.save()
            obj.current_audit_users.clear()
            obj.sealmakingrecord_set.filter(state='unaudit').delete()
        else:
            obj = SealMaking.objects.create(
                apply_user=apply_user,
                company=company,
                making_number=making_number,
                plan_seal_name=seal_name,
                reason=reason,
                fj_number=fj_number
            )
        bgs_obj = Company.objects.get(id=80).head_people

        SealMakingRecord.objects.create(node="one", state='unaudit', audit_people=bgs_obj, parent_id=obj)
        obj.current_audit_users.add(bgs_obj)
        if company.id != 80:
            try:
                fgld = company.leaders_id
            except:
                returnDict = {'code': 500, 'message': '科室分管领导未设置，请联系管理员设置'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            SealMakingRecord.objects.create(node="two", state='unaudit', audit_people=fgld, parent_id=obj)
        try:
            seal_person = Staffing.objects.get(station='印章刻制').post_personnel.all().first()
        except:
            returnDict = {'code': 500, 'message': '系统未设置 ”印章刻制“ 一职，请联系管理员设置'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        SealMakingRecord.objects.create(node="three", state='unaudit', audit_people=seal_person, parent_id=obj)

        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "印章刻制"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '提交成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SealMakingListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "table_name": "finance_sealmaking"}
        return render(request, 'finance/seal_making_list_view.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", None)  # 查询标题
        tab = request.POST.get("tab", 'apply')  # apply 我的申请 audit 我的待办 already 我的已办
        objs = user.sealmaking_set.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'plan_seal_name': obj.plan_seal_name,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='seal_making_draft_view?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>" if obj.state == 'draft' else (
                          f"<a href='seal_making_detail_view?id={obj.id}'>查看</a> | <a href='seal_making_detail_view?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state in [
                              'one', 'two', 'three'] else (f"<a href='seal_making_detail_view?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"if obj.state == 'stop' else f"<a href='seal_making_detail_view?id={obj.id}'>查看</a>")),
                      'state': obj.get_state_str(), "title": "印章刻制申请"}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class SealMakingDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = SealMaking.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.sealmakingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealmakingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                          os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three'] and request.user == obj.apply_user else 'false',
                   'uuid': uuid.uuid1(), 'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }

        return render(request, 'finance/seal_making_detail_view.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "印章刻制")
        except:
            pass
        obj = SealMaking.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.sealmakingrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                if obj.sealmakingrecord_set.filter(node='two', state='unaudit'):
                    next_audit_record = obj.sealmakingrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                else:
                    next_audit_record = obj.sealmakingrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'two':
            audit_record = obj.sealmakingrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.sealmakingrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'three':
            audit_record = obj.sealmakingrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "印章刻制"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.reason[:15] + "……" if len(obj.reason) > 15 else obj.reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class SealMakingRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = SealMaking.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的请假申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.sealmakingrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的请假申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的请假申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class SealMakingDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = SealMaking.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.sealmakingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.sealmakingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                          os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (
                                                obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two',
                                                       'three'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two',
                                                      'three'] and request.user == obj.apply_user else 'false',
                   'uuid': uuid.uuid1(), 'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace(
                       "\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }

        return render(request, 'finance/seal_making_draft_view.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        apply_user = request.user
        company = request.user.company
        seal_name = request.POST.get("seal_name", None)
        making_number = request.POST.get("making_number", None)
        reason = request.POST.get("reason", None)
        fj_number = request.POST.get('uuid', None)
        if id:
            obj = SealMaking.objects.get(id=int(id))
            obj.apply_user = apply_user
            obj.company = company
            obj.making_number = making_number
            obj.plan_seal_name = seal_name
            obj.reason = reason
            obj.fj_number = fj_number
            obj.state = "draft"
            obj.can_revise = "1"
            obj.save()
        else:
            obj = SealMaking.objects.create(
                apply_user=apply_user,
                company=company,
                making_number=making_number,
                plan_seal_name=seal_name,
                reason=reason,
                fj_number=fj_number,
                state="draft"
            )
        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 用印快捷授权列表页
class QuickAuthorizationList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "table_name": "finance_sealmaking"}
        return render(request, 'finance/QuickAuthorizationList.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = QuickAuthorization.objects.filter(apply_user=user).order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.authorization_type,
                      'company': obj.company.name,
                      'seal_name': ', '.join([u.seal_name for u in obj.seal_name.all()]),
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='QuickAuthorizationDarf.html?id={obj.id}'>编辑</a> | <a href='javascript:;' onclick='del_draft({obj.id})' style='color:red;'>删除</a>" if obj.state == 'draft'
                      else f"<a href='QuickAuthorizationDetail.html?id={obj.id}'>查看</a>" if obj.can_revise == '1' and obj.state not in ['draft', "stop"]
                      else f"<a href='QuickAuthorizationDetail.html?id={obj.id}'>查看</a> |  <a href='javascript:;' onclick='del_draft({obj.id})' style='color:red;'>删除</a>" if obj.state == "stop"
                      else f"<a href='QuickAuthorizationDetail.html?id={obj.id}'>查看</a>", 'state': obj.get_state_str(), "title": json.loads(obj.reason)[0]["neirong"]} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 印章快捷授权申请页
class QuickAuthorizationIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        quick_obj = []

        seal_obj, shenqing_type = [], ""
        if request.user.group.id == 2:
            QuickObj = QuickAuthorizationSeal.objects.filter(can_related='1', authorization_type='1', select_leader=request.user)
            try:
                quick_obj = QuickObj.first()
                thoriza_obj = quick_obj.quickauthorizationapplicationcategory_set.filter(authorization_type='0')
                for t in thoriza_obj:
                    if t.seal_id not in seal_obj:
                        seal_obj.append(t.seal_id)
                shenqing_type = "法人授权"
            except:
                pass
        else:
            QuickObj = QuickAuthorizationSeal.objects.filter(can_related='1', authorization_type='2', company=request.user.company)
            try:
                for i in QuickObj:
                    ncat_obj = i.quickauthorizationapplicationcategory_set.filter(authorization_type='0')
                    if ncat_obj.count():
                        quick_obj = i
                        for j in ncat_obj:
                            if j.seal_id not in seal_obj:
                                seal_obj.append(j.seal_id)
                        shenqing_type = "分管授权"
                        break
            except:
                pass

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "apply_time": datetime.now(), "seal_obj": seal_obj, "shenqing_type": shenqing_type,
                   "quick_obj": json.loads(quick_obj.detail_json) if quick_obj else [], "obj": quick_obj, "fj_number": uuid.uuid4()}
        return render(request, 'finance/QuickAuthorizationIndex.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        apply_user = request.user
        company = request.user.company
        reason = request.POST.get("detail_json", None)
        admin_flag = request.POST.get("admin", None)
        authorization_type = request.POST.get("authorization_type", None)
        quick_id = request.POST.get("quick_id", None)
        take_effect_time = request.POST.get("take_effect_time", None)
        lose_efficacy_time = request.POST.get("lose_efficacy_time", None)
        fj_number = request.POST.get("fj_number", "")

        quick_obj = QuickAuthorizationSeal.objects.get(id=int(quick_id))
        AuthorizedDepartment = quick_obj.company.head_people                                        # 授权科室负责人

        authorized_detail_json = json.loads(quick_obj.detail_json)
        neirong = json.loads(reason)[0]["neirong"]                                  # 分管领导/科主任申请授权内容

        for tt in authorized_detail_json:
            for kk in tt["neirong"]:
                if kk["neirong"] == neirong:
                    kk["empower"] = '1'
        quick_obj.detail_json = json.dumps(authorized_detail_json)
        quick_obj.save()

        ory_obj = QuickAuthorizationApplicationCategory.objects.filter(category=neirong.strip(), quick=quick_obj)

        HandledByPeople = ""
        if ory_obj:
            AuthorObj = QuickAuthorizationApplicationCategory.objects.get(id=ory_obj.first().id)
            HandledByPeople = AuthorObj.authorized_person
            AuthorObj.authorization_type = '1'
            AuthorObj.save()
            print(ory_obj.count(), "保存成功！", AuthorObj.authorization_type, AuthorObj.id)

        apply_flag = True
        cate_obj = QuickAuthorizationApplicationCategory.objects.filter(authorization_type='0', quick=quick_obj).count()
        if cate_obj:
            apply_flag = False

        if id:
            obj = QuickAuthorization.objects.get(id=int(id))
            obj.reason = reason
            obj.quick = quick_obj
            if HandledByPeople:
                obj.HandledBy = HandledByPeople
            obj.authorization_type = authorization_type
            if admin_flag:
                obj.save()
                returnDict = {'code': 200, 'message': '修改成功！'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            else:
                obj.seal_name.clear()
                obj.current_audit_users.clear()
                obj.quickauthorizationrecord_set.filter(state='unaudit').delete()
        else:
            if HandledByPeople:
                obj = QuickAuthorization.objects.create(apply_user=apply_user, company=company, reason=reason, authorization_type=authorization_type, take_effect_time=take_effect_time, lose_efficacy_time=lose_efficacy_time, quick=quick_obj, HandledBy=HandledByPeople, fj_number=fj_number)
            else:
                obj = QuickAuthorization.objects.create(apply_user=apply_user, company=company, reason=reason, authorization_type=authorization_type, take_effect_time=take_effect_time, lose_efficacy_time=lose_efficacy_time, quick=quick_obj, fj_number=fj_number)

        for i in json.loads(reason):
            obj.seal_name.add(seal.objects.get(id=int(i["yinzhang"])))

        sjk_obj = Company.objects.get(id=22).head_people
        flag = True
        # 审计科审核
        if ory_obj.first().authorized_person != sjk_obj:
            QuickAuthorizationRecord.objects.create(node="one", state='unaudit', audit_people=sjk_obj, parent_id=obj)
            obj.current_audit_users.add(sjk_obj)
            obj.state = 'one'
            flag = False

        if authorization_type == "法人授权":
            # 院长审核
            QuickAuthorizationRecord.objects.create(node="two", state='unaudit', audit_people=Staffing.objects.get(station='院长').post_personnel.all().first(), parent_id=obj)
            if flag:
                obj.current_audit_users.add(Staffing.objects.get(station='院长').post_personnel.all().first())
                obj.state = 'two'

            # 分管领导审核
            QuickAuthorizationRecord.objects.create(node="three", state='unaudit', audit_people=apply_user, parent_id=obj)

            # 科主任接收
            QuickAuthorizationRecord.objects.create(node="four", state='unaudit', audit_people=AuthorizedDepartment, parent_id=obj)

            if json.loads(reason)[0]['leval'] == '三级授权':
                if HandledByPeople and AuthorizedDepartment != HandledByPeople:
                    QuickAuthorizationRecord.objects.create(node="five", state='unaudit', audit_people=HandledByPeople, parent_id=obj)

        else:
            # 分管领导审核
            LeaderSept = ory_obj.first().quick.select_leader
            QuickAuthorizationRecord.objects.create(node="three", state='unaudit', audit_people=LeaderSept, parent_id=obj)
            if flag:
                obj.current_audit_users.add(LeaderSept)
                obj.state = 'three'

            # 科主任接收
            QuickAuthorizationRecord.objects.create(node="four", state='unaudit', audit_people=apply_user, parent_id=obj)

            if json.loads(reason)[0]['leval'] == '二级授权':
                if HandledByPeople and AuthorizedDepartment != HandledByPeople:
                    QuickAuthorizationRecord.objects.create(node="five", state='unaudit', audit_people=HandledByPeople, parent_id=obj)

        obj.save()
        if apply_flag:
            quick_obj.can_related='0'
            quick_obj.save()
        returnDict = {'code': 200, 'message': '提交成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class QuickAuthorizationDarf(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)

        obj = QuickAuthorization.objects.get(id=id)

        quick_obj = []

        seal_obj, shenqing_type = [], ""
        if request.user.group.id == 2:
            QuickObj = QuickAuthorizationSeal.objects.filter(can_related='1', authorization_type='1',
                                                             select_leader=request.user)
            try:
                quick_obj = QuickObj.first()
                thoriza_obj = quick_obj.quickauthorizationapplicationcategory_set.filter(authorization_type='0')
                for t in thoriza_obj:
                    if t.seal_id not in seal_obj:
                        seal_obj.append(t.seal_id)
                shenqing_type = "法人授权"
            except:
                pass
        else:
            QuickObj = QuickAuthorizationSeal.objects.filter(can_related='1', authorization_type='2',
                                                             company=request.user.company)
            try:
                for i in QuickObj:
                    ncat_obj = i.quickauthorizationapplicationcategory_set.filter(authorization_type='0')
                    if ncat_obj.count():
                        quick_obj = i
                        for j in ncat_obj:
                            if j.seal_id not in seal_obj:
                                seal_obj.append(j.seal_id)
                        shenqing_type = "分管授权"
                        break
            except:
                pass

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "apply_time": datetime.now(), "seal_obj": seal_obj, "shenqing_type": shenqing_type,
                   "quick_obj": json.loads(quick_obj.detail_json) if quick_obj else [], "obj": quick_obj, "shortcut_obj": obj, 'reason': json.loads(obj.reason), "file_list": file_list}
        return render(request, 'finance/QuickAuthorizationDarf.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        apply_user = request.user
        company = request.user.company
        reason = request.POST.get("detail_json", None)
        authorization_type = request.POST.get("authorization_type", None)
        take_effect_time = request.POST.get("take_effect_time", None)
        lose_efficacy_time = request.POST.get("lose_efficacy_time", None)
        fj_number = request.POST.get("fj_number", "")

        if id:
            obj = QuickAuthorization.objects.get(id=int(id))
            obj.reason = reason
            obj.save()
        else:
            obj = QuickAuthorization.objects.create(apply_user=apply_user, company=company, reason=reason, authorization_type=authorization_type, take_effect_time=take_effect_time,
                                                    lose_efficacy_time=lose_efficacy_time, fj_number=fj_number)
        obj.state = "draft"
        obj.seal_name.clear()
        obj.save()
        for i in json.loads(reason):
            if int(i["yinzhang"]):
                obj.seal_name.add(seal.objects.get(id=int(i["yinzhang"])))

        returnDict = {'code': 200, 'message': '保存成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 印章快捷授权详情
class QuickAuthorizationDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        seal_obj = seal.objects.all()
        obj = QuickAuthorization.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.quickauthorizationrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.quickauthorizationrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        if obj.authorization_type == '法人授权':
            if obj.state in ["one", "two"]:
                ApprovalType = "approval"
            else:
                ApprovalType = "receive"
        else:
            if obj.state in ["one", "three"]:
                ApprovalType = "approval"
            else:
                ApprovalType = "receive"

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""), "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "main_file_list": file_list,
                   "obj": obj, 'audit_dic': audit_dic, "seal_obj": seal_obj, 'seal_list': [i.id for i in obj.seal_name.all()], 'seal_name': ', '.join([i.seal_name for i in obj.seal_name.all()]),
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false', 'reason': json.loads(obj.reason), "ApprovalType": ApprovalType,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five'] and request.user == obj.apply_user else 'false', 'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""}
        return render(request, 'finance/QuickAuthorizationDetail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过

        obj = QuickAuthorization.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)

        if obj.state == 'one':
            message_str = '审批成功！'
            obj.current_audit_users.clear()
            audit_record = obj.quickauthorizationrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                if obj.quickauthorizationrecord_set.filter(node='two', state='unaudit'):
                    next_audit_record = obj.quickauthorizationrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                else:
                    next_audit_record = obj.quickauthorizationrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            message_str = '审批成功！'
            obj.current_audit_users.clear()
            audit_record = obj.quickauthorizationrecord_set.filter(node='two', state='unaudit').first()

            if state == 'audit':
                next_audit_record = obj.quickauthorizationrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)

            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            message_str = '接收成功！'
            obj.current_audit_users.clear()
            audit_record = obj.quickauthorizationrecord_set.filter(node='three', state='unaudit', audit_people=request.user).first()

            if obj.quickauthorizationrecord_set.filter(node='four', state='unaudit'):
                next_audit_record = obj.quickauthorizationrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)

            else:
                obj_state = 'seven'
                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                MakeCopy.objects.create(recipient=BGS_appave, process_id=obj.id, type='c')
                GzbZhuRen = Company.objects.get(id=3).head_people
                MakeCopy.objects.create(recipient=GzbZhuRen, process_id=obj.id, type='c')
            state = 'audit'

        elif obj.state == 'four':
            message_str = '接收成功！'
            obj.current_audit_users.clear()
            audit_record = obj.quickauthorizationrecord_set.filter(node='four', state='unaudit', audit_people=request.user).first()

            if obj.quickauthorizationrecord_set.filter(node='five', state='unaudit'):
                next_audit_record = obj.quickauthorizationrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)

            else:
                obj_state = 'seven'
                BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
                MakeCopy.objects.create(recipient=BGS_appave, process_id=obj.id, type='c')
                GzbZhuRen = Company.objects.get(id=3).head_people
                MakeCopy.objects.create(recipient=GzbZhuRen, process_id=obj.id, type='c')
            state = 'audit'

        elif obj.state == 'five':
            message_str = '接收成功！'
            obj.current_audit_users.clear()
            obj_state = 'seven'
            state = 'audit'
            audit_record = obj.quickauthorizationrecord_set.filter(node='five', state='unaudit', audit_people=request.user).first()
            BGS_appave = Staffing.objects.get(station='印章管理员').post_personnel.all().first()
            MakeCopy.objects.create(recipient=BGS_appave, process_id=obj.id, type='c')
            GzbZhuRen = Company.objects.get(id=3).head_people
            MakeCopy.objects.create(recipient=GzbZhuRen, process_id=obj.id, type='c')

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        if audit_record:
            audit_record.update_time = datetime.now()
            audit_record.state = state
            audit_record.audit_note = audit_note
            audit_record.save()
        returnDict = {'code': 200, 'message': message_str}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class QuickAuthorizationStop(View):
    def post(self, request):
        id = request.POST.get('id', None)
        types = request.POST.get('types', 'stop')  # stop 终止 delete 删除
        obj = QuickAuthorization.objects.get(id=int(id))
        if types == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的流程不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
                returnData = {'code': 200, 'message': '终止成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            obj.current_audit_users.clear()
            obj.quickauthorizationrecord_set.all().delete()
            obj.quickauthorizationauthorized_set.all().delete()
            obj.audit_users_already.clear()
            obj.seal_name.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

# 图书/报刊/杂志征订列表页
class BookSubscriptionList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'finance/BookSubscriptionList.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = user.booksubscription_set.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='BookSubscriptionDarf.html?id={obj.id}'>编辑</a> | <a href='javascript:;' onclick='del_draft({obj.id})' style='color:red;'>删除</a>" if obj.state == 'draft'
                      else f"<a href='BookSubscriptionDetail.html?id={obj.id}'>查看</a> | <a href='BookSubscriptionDetail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state != 'draft'
                      else f"<a href='BookSubscriptionDetail.html?id={obj.id}'>查看</a> |  <a href='javascript:;' onclick='del_draft({obj.id})' style='color:red;'>删除</a>" if obj.state == "stop" else f"<a href='BookSubscriptionDetail.html?id={obj.id}'>查看</a>",
                      'state': obj.get_state_str(), "title": "图书/报刊/杂志征订"}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class BookSubscriptionIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "uuid": uuid.uuid4()}
        return render(request, 'finance/BookSubscriptionIndex.html', context)


    def post(self, request):
        id = request.POST.get('id', None)
        apply_user = request.user
        company = request.user.company
        BookBuyList = request.POST.get("BookBuyList", None)
        PressBuyList = request.POST.get("PressBuyList", None)
        fj_number = request.POST.get("fj_number", None)
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "图书/报刊/杂志征订")
        except:
            pass
        if id:
            obj = BookSubscription.objects.get(id=int(id))
            obj.apply_user = apply_user
            obj.company = company
            obj.reason = PressBuyList
            obj.book_buy = BookBuyList
            obj.current_audit_users.clear()
            obj.booksubscriptionrecord_set.filter(state='unaudit').delete()
            obj.save()
        else:
            obj = BookSubscription.objects.create(apply_user=apply_user, company=company, reason=PressBuyList, book_buy=BookBuyList, fj_number=fj_number)

        flag = True
        director_people = apply_user.company.head_people
        if apply_user != director_people:
            BookSubscriptionRecord.objects.create(node="one", state='unaudit', audit_people=director_people, parent_id=obj)
            obj.state = 'one'
            flag = False
            obj.current_audit_users.add(director_people)

        two_step = Staffing.objects.get(station='图书管理员').post_personnel.all()
        for two in two_step:
            BookSubscriptionRecord.objects.create(node="two", state='unaudit', audit_people=two, parent_id=obj)
            if flag:
                obj.state = 'two'
                obj.current_audit_users.add(two)

        Batjk = Company.objects.get(id=24)
        three_step = Batjk.head_people
        BookSubscriptionRecord.objects.create(node="three", state='unaudit', audit_people=three_step, parent_id=obj)
        BookSubscriptionRecord.objects.create(node="four", state='unaudit', audit_people=Batjk.leaders_id, parent_id=obj)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "后勤管理"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = "图书/报刊/杂志征订"
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '提交成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class BookSubscriptionDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = BookSubscription.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.booksubscriptionrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                              audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.booksubscriptionrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list, 'flow_dict': flow_dict, "revise": revise,
                   'reason': json.loads(obj.reason), 'book_buy': json.loads(obj.book_buy),
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/BookSubscriptionDetail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "图书/报刊/杂志征订")
        except:
            pass
        obj = BookSubscription.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.booksubscriptionrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.booksubscriptionrecord_set.filter(node='two', state='unaudit')
                obj_state = 'two'
                for i in next_audit_record:
                    obj.current_audit_users.add(i.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.booksubscriptionrecord_set.filter(node='two', state='unaudit', audit_people=request.user).first()
            if state == 'audit':
                next_audit_record = obj.booksubscriptionrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
            obj.booksubscriptionrecord_set.filter(~Q(audit_people=request.user), node='two', state='unaudit').delete()

        elif obj.state == 'three':
            audit_record = obj.booksubscriptionrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.booksubscriptionrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.booksubscriptionrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "后勤管理"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = "图书/报刊/杂志征订"
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '审批成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class BookSubscriptionDarf(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = BookSubscription.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'reason': json.loads(obj.reason), 'book_buy': json.loads(obj.book_buy),
                   'flow_dict': flow_dict, "revise": revise}
        return render(request, 'finance/BookSubscriptionDarf.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        apply_user = request.user
        company = request.user.company
        BookBuyList = request.POST.get("BookBuyList", None)
        PressBuyList = request.POST.get("PressBuyList", None)
        fj_number = request.POST.get("fj_number", None)
        if id:
            obj = BookSubscription.objects.get(id=int(id))
            obj.apply_user = apply_user
            obj.company = company
            obj.reason = PressBuyList
            obj.book_buy = BookBuyList
        else:
            obj = BookSubscription.objects.create(apply_user=apply_user, company=company, reason=PressBuyList, book_buy=BookBuyList, fj_number=fj_number)

        obj.state = 'draft'
        obj.save()
        returnDict = {'code': 200, 'message': '提交成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class BookSubscriptionStop(View):
    def post(self, request):
        id = request.POST.get('id', None)
        types = request.POST.get('types', 'stop')  # stop 终止 delete 删除
        obj = BookSubscription.objects.get(id=int(id))
        if types == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的流程不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
                returnData = {'code': 200, 'message': '终止成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            obj.current_audit_users.clear()
            obj.booksubscriptionrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class PartyBuildingFundsList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'finance/party_building_funds_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = PartyBuilding.objects.filter(apply_user=user).order_by('-create_time')
        data_list = [{'id': obj.id, 'apply_user': obj.apply_user.real_name, 'company': obj.company.name, 'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='PartyBuildingFundsDarf.html?id={obj.id}'>编辑</a> | <a href='javascript:;' onclick='del_draft({obj.id})' style='color:red;'>删除</a>" if obj.state == 'draft'
                      else f"<a href='PartyBuildingFundsDetail.html?id={obj.id}'>查看</a> | <a href='PartyBuildingFundsDetail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state not in ['draft', 'stop']
                      else f"<a href='PartyBuildingFundsDetail.html?id={obj.id}'>查看</a> |  <a href='javascript:;' onclick='del_draft({obj.id})' style='color:red;'>删除</a>" if obj.state == "stop" else f"<a href='PartyBuildingFundsDetail.html?id={obj.id}'>查看</a>",
                      'state': obj.get_state_str(), "title": obj.application_reason if obj.application_reason else json.loads(obj.pay_detail)[0]["b"] if json.loads(obj.pay_detail) else "党建经费"}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class PartyBuildingFundsIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        branch_review_obj = Staffing.objects.get(station='支部书记').post_personnel.all()
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'uuid': uuid.uuid1(), "branch_review_obj": branch_review_obj}
        return render(request, 'finance/PartyBuildingFundsIndex.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        apply_user = request.user
        company = request.user.company
        paydetail = request.POST.get("paydetail", None)
        fj_number = request.POST.get("uuid", None)
        total_money = request.POST.get("total_money", None)
        daxie = request.POST.get("daxie", None)
        branch_review = request.POST.get("branch_review", None)
        dep_type = request.POST.get("dep_type", '1')
        TypeId = request.POST.get("TypeId", None)
        payee = request.POST.get("payee", "")
        account_number = request.POST.get("account_number", "")
        application_reason = request.POST.get("application_reason", "")
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "党建经费")
        except:
            pass
        if id:
            obj = PartyBuilding.objects.get(id=int(id))
            obj.apply_user = apply_user
            obj.company = company
            if branch_review != '000':
                obj.branch_review = User.objects.get(id=int(branch_review))
            obj.pay_detail = paydetail
            obj.total_amount = total_money
            obj.daxie = daxie
            obj.application_reason = application_reason
            obj.fj_number = fj_number
            obj.dep_type = dep_type
            obj.TypeId = TypeId
            obj.payee = payee
            obj.account_number = account_number
            obj.current_audit_users.clear()
            obj.partybuildingrecord_set.filter(state='unaudit').delete()
            obj.save()
        else:
            if branch_review != '000':
                obj = PartyBuilding.objects.create(apply_user=apply_user, company=company, branch_review=User.objects.get(id=int(branch_review)), pay_detail=paydetail, total_amount=total_money, daxie=daxie, fj_number=fj_number, TypeId=TypeId, dep_type=dep_type, payee=payee, account_number=account_number, application_reason=application_reason)
            else:
                obj = PartyBuilding.objects.create(apply_user=apply_user, company=company, pay_detail=paydetail, total_amount=total_money, daxie=daxie, fj_number=fj_number, TypeId=TypeId, dep_type=dep_type, payee=payee, account_number=account_number, application_reason=application_reason)

        flag = True
        if branch_review != '000':
            one_appove = User.objects.get(id=int(branch_review))
            if company.id not in [3, 80] and request.user != one_appove:
                PartyBuildingRecord.objects.create(node="one", state='unaudit', audit_people=one_appove, parent_id=obj, audit_note='')
                obj.state = "one"
                obj.current_audit_users.add(User.objects.get(id=int(branch_review)))
                flag = False

        two_prave = Company.objects.get(id=3).head_people
        PartyBuildingRecord.objects.create(node="two", state='unaudit', audit_people=two_prave, parent_id=obj, audit_note='')
        if flag:
            obj.state = "two"
            obj.current_audit_users.add(two_prave)

        PartyBuildingRecord.objects.create(node="three", state='unaudit', audit_people=Company.objects.get(id=3).leaders_id, parent_id=obj, audit_note='')

        four_prave = Company.objects.get(id=23).head_people
        PartyBuildingRecord.objects.create(node="four", state='unaudit', audit_people=four_prave, parent_id=obj, audit_note='')

        five_prave = Company.objects.get(id=23).leaders_id if float(total_money.replace(",", '')) <= 10000 else Staffing.objects.get(station="书记").post_personnel.all().first()
        PartyBuildingRecord.objects.create(node="five", state='unaudit', audit_people=five_prave, parent_id=obj, audit_note='')

        PartyBuildingRecord.objects.create(node="six", state='unaudit', audit_people=Staffing.objects.get(station="财务支付").post_personnel.all().first(), parent_id=obj, audit_note='')

        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "党建经费"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.application_reason[:15] + "……" if len(obj.application_reason) > 15 else obj.application_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '提交成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class PartyBuildingFundsDarf(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        obj = PartyBuilding.objects.get(id=id)
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]
        branch_review_obj = Staffing.objects.get(station='支部书记').post_personnel.all()
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "file_list": file_list, "pay_detail": json.loads(obj.pay_detail), "branch_review_obj": branch_review_obj,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/PartyBuildingFundsDarf.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        apply_user = request.user
        company = request.user.company
        paydetail = request.POST.get("paydetail", None)
        fj_number = request.POST.get("uuid", None)
        total_money = request.POST.get("total_money", None)
        daxie = request.POST.get("daxie", None)
        branch_review = request.POST.get("branch_review", None)
        dep_type = request.POST.get("dep_type", None)
        TypeId = request.POST.get("TypeId", None)
        admin_flag = request.POST.get("admin_flag", None)
        payee = request.POST.get("payee", "")
        account_number = request.POST.get("account_number", "")
        application_reason = request.POST.get("application_reason", "")
        if id:
            obj = PartyBuilding.objects.get(id=int(id))
            obj.pay_detail = paydetail
            obj.total_amount = total_money
            obj.daxie = daxie
            obj.fj_number = fj_number
            obj.dep_type = dep_type
            obj.TypeId = TypeId
            obj.payee = payee
            obj.account_number = account_number
            obj.application_reason = application_reason
            if branch_review != '000':
                obj.branch_review = User.objects.get(id=int(branch_review))
        else:
            if branch_review != '000':
                obj = PartyBuilding.objects.create(apply_user=apply_user, company=company, branch_review=User.objects.get(id=int(branch_review)), pay_detail=paydetail, total_amount=total_money, daxie=daxie, fj_number=fj_number, TypeId=TypeId, dep_type=dep_type, payee=payee, account_number=account_number, application_reason=application_reason)
            else:
                obj = PartyBuilding.objects.create(apply_user=apply_user, company=company, pay_detail=paydetail, total_amount=total_money, daxie=daxie, fj_number=fj_number, TypeId=TypeId, dep_type=dep_type, payee=payee, account_number=account_number, application_reason=application_reason)
        if not admin_flag:
            obj.state='draft'
        obj.save()
        returnDict = {'code': 200, 'message': '保存成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class PartyBuildingFundsStop(View):
    def post(self, request):
        id = request.POST.get('id', None)
        types = request.POST.get('types', 'stop')  # stop 终止 delete 删除
        obj = PartyBuilding.objects.get(id=int(id))
        if types == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的流程不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
                returnData = {'code': 200, 'message': '终止成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            obj.current_audit_users.clear()
            obj.partybuildingrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")

class PartyBuildingFundsDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = PartyBuilding.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.partybuildingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.partybuildingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list, "pay_detail": json.loads(obj.pay_detail),
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six"] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false',
                   'flow_dict': flow_dict, "revise": revise, "branch_review_obj": Staffing.objects.get(station='支部书记').post_personnel.all(),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/PartyBuildingFundsDetail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "党建经费")
        except:
            pass
        obj = PartyBuilding.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.partybuildingrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                if obj.partybuildingrecord_set.filter(node='two'):
                    next_audit_record = obj.partybuildingrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                    obj.current_audit_users.add(next_audit_record.audit_people)

                else:
                    next_audit_record = obj.partybuildingrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                    obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.partybuildingrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.partybuildingrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.partybuildingrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.partybuildingrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.partybuildingrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.partybuildingrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.partybuildingrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.partybuildingrecord_set.filter(node='six', state='unaudit').first()
                obj_state = 'six'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.partybuildingrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "党建经费"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.application_reason[:15] + "……" if len(
            obj.application_reason) > 15 else obj.application_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ObjectAuditList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "table_name": "finance_objectaudit"}
        return render(request, 'finance/object_audit_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        search_data = request.POST.get("search_data", '')  # 查询标题
        objs = user.objectaudit_set.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='object_audit_draft_view?id={obj.id}'>编辑</a>" if obj.state == 'draft'
                      else f"<a href='object_audit_detail_view?id={obj.id}'>查看</a> | <a href='object_audit_detail_view?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state != 'draft'
                      else f"<a href='object_audit_detail_view?id={obj.id}'>查看</a>" if obj.state == "stop" else f"<a href='object_audit_detail_view?id={obj.id}'>查看</a>",
                      'state': obj.get_state_str(), "title": obj.work_name}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ObjectAuditIndexView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "uuid": uuid.uuid1(), 'date': datetime.now().strftime("%Y-%m-%d %H:%M")}
        return render(request, 'finance/object_audit_index_view.html', context)

    def post(self, request):
        id = request.POST.get("id", None)
        apply_user = request.user
        company = request.user.company
        w_time = request.POST.get('w_time', None)  # 填表时间
        r_time = request.POST.get("r_time", None)  # 收文时间
        work_name = request.POST.get("work_name", None)  # 项目名称
        describe = request.POST.get("describe", None)  # 项目概述
        audit_ask = request.POST.get("audit_ask", None)  # 送审要求
        htje = request.POST.get("htje", None)
        sgfzj = request.POST.get("sgfzj", None)
        bmzj = request.POST.get("bmzj", None)
        fj_number = request.POST.get("fj_number", None)
        admin_flag = request.POST.get("admin", '')
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "项目审计送审审批")
        except:
            pass
        if id:
            obj = ObjectAudit.objects.get(id=int(id))
            obj.w_time = w_time
            obj.r_time = r_time
            obj.work_name = work_name
            obj.describe = describe
            obj.audit_ask = audit_ask
            obj.htje = htje
            obj.sgfzj = sgfzj
            obj.bmzj = bmzj
            obj.fj_number = fj_number

            if not admin_flag:
                obj.current_audit_users.clear()
                obj.objectauditrecord_set.filter(state='unaudit').delete()
                obj.state = "one" if apply_user != company.head_people else "two"
                if apply_user == company.head_people:
                    ObjectAuditRecord.objects.create(node="two", state='unaudit', audit_people=company.leaders_id, parent_id=obj, audit_note='')
                    obj.current_audit_users.add(company.leaders_id)
                else:
                    ObjectAuditRecord.objects.create(node="one", state='unaudit', audit_people=company.head_people, parent_id=obj, audit_note='')
                    ObjectAuditRecord.objects.create(node="two", state='unaudit', audit_people=company.leaders_id, parent_id=obj, audit_note='')
                    obj.current_audit_users.add(company.head_people)
            obj.save()
        else:
            ksfzr = company.head_people
            if apply_user == ksfzr:
                obj = ObjectAudit.objects.create(apply_user=apply_user, company=company, w_time=w_time, r_time=r_time,
                                                 work_name=work_name, fj_number=fj_number, describe=describe,
                                                 audit_ask=audit_ask, htje=htje, sgfzj=sgfzj, bmzj=bmzj, state="two")
                ObjectAuditRecord.objects.create(node="two", state='unaudit',
                                                 audit_people=company.leaders_id, parent_id=obj, audit_note='')
                obj.current_audit_users.add(company.leaders_id)
            else:
                obj = ObjectAudit.objects.create(apply_user=apply_user, company=company, w_time=w_time, r_time=r_time,
                                                 work_name=work_name, fj_number=fj_number, describe=describe,
                                                 audit_ask=audit_ask, htje=htje, sgfzj=sgfzj, bmzj=bmzj, state="one")
                ObjectAuditRecord.objects.create(node="one", state='unaudit',
                                                 audit_people=company.head_people, parent_id=obj, audit_note='')
                ObjectAuditRecord.objects.create(node="two", state='unaudit',
                                                 audit_people=company.leaders_id, parent_id=obj, audit_note='')
                obj.current_audit_users.add(company.head_people)
            obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "审计送审"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.work_name[:15] + "……" if len(obj.work_name) > 15 else obj.work_name
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnDict = {'code': 200, 'message': '提交成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


# 项目送审详情
class ObjectAuditDetailView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ObjectAudit.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.objectauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime(
                                                      "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(
                                                      audit_obj.audit_people.signature_picture) if (
                                                          audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.objectauditrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))),
                                             'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime(
                                                  "%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(
                                                  audit_obj.audit_people.signature_picture) if (
                                                      audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(
                          os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two'] and request.user == obj.apply_user else 'false',
                   'uuid': uuid.uuid1(), 'flow_dict': flow_dict, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }

        return render(request, 'finance/obj_audit_detail_view.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "项目审计送审审批")
        except:
            pass
        obj = ObjectAudit.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.objectauditrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.objectauditrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        elif obj.state == 'two':
            audit_record = obj.objectauditrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
                sjk_obj = Company.objects.get(id=22).head_people
                MakeCopy.objects.create(recipient=sjk_obj, process_id=obj.id, type='i')
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)
        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "审计送审"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.work_name[:15] + "……" if len(obj.work_name) > 15 else obj.work_name
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class ObjectAuditDraftView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        obj = ObjectAudit.objects.get(id=id)
        if obj.fj_number:
            file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/",
                                                                                 ""),
                 "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for
                atta_obj in
                Topicsattachments.objects.filter(topics_number=obj.fj_number)]
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, 'obj': obj, 'file_list': file_list, "uuid": obj.fj_number}
        else:
            context = {'realname': request.user.real_name, 'position': request.user.post,
                       'department': request.user.company.name, 'obj': obj, 'uuid': uuid.uuid1()}
        return render(request, 'finance/object_audit_draft_view.html', context)

    def post(self, request):
        id = request.POST.get("id", None)
        apply_user = request.user
        company = request.user.company
        w_time = request.POST.get('w_time', None)  # 填表时间
        r_time = request.POST.get("r_time", None)  # 收文时间
        work_name = request.POST.get("work_name", None)  # 项目名称
        describe = request.POST.get("describe", None)  # 项目概述
        audit_ask = request.POST.get("audit_ask", None)  # 送审要求
        htje = request.POST.get("htje", None)  # 合同金额
        sgfzj = request.POST.get("sgfzj", None)  # 施工方结算造价
        bmzj = request.POST.get("bmzj", None)  # 本部门认定造价
        fj_number = request.POST.get("fj_number", None)
        if id:
            obj = ObjectAudit.objects.get(id=int(id))
            obj.apply_user = apply_user
            obj.company = company
            obj.w_time = w_time
            obj.r_time = r_time
            obj.work_name = work_name
            obj.describe = describe
            obj.audit_ask = audit_ask
            obj.htje = htje
            obj.sgfzj = sgfzj
            obj.bmzj = bmzj
            obj.fj_number = fj_number
            obj.current_audit_users.clear()
            obj.objectauditrecord_set.filter(state='unaudit').delete()
            obj.save()
        else:
            obj = ObjectAudit.objects.create(apply_user=apply_user, company=company, w_time=w_time, r_time=r_time,
                                             work_name=work_name, fj_number=fj_number, describe=describe,
                                             audit_ask=audit_ask, htje=htje, sgfzj=sgfzj, bmzj=bmzj, state="draft")
            obj.save()
        returnDict = {'code': 200, 'message': '保存成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ObjectAuditRevokeView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        state = request.POST.get('state', None)  # stop 终止 recall 撤回 cancel 作废
        obj = ObjectAudit.objects.get(id=int(id))
        if state == 'cancel':
            if obj.state != 'seven':
                returnData = {'code': 500, 'message': '作废失败，只有为审批完毕的请假申请才能作废！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.state = 'cancel'
                obj.save()
        elif state == 'recall':
            if obj.sealmakingrecord_set.filter(state__in=['draft', 'audit']).count() > 0:
                returnData = {'code': 500, 'message': '撤回失败，只有未审批的请假申请才能撤回！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'recall'
                obj.save()
        elif state == 'stop':
            if obj.state == 'seven':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的请假申请不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
        else:
            returnData = {'code': 500, 'message': '操作失败，状态错误！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class delete_object_flow(View):
    def post(self, request):
        flow_id = request.POST.get('id', "")
        obj = ObjectAudit.objects.get(id=int(flow_id))
        if obj.state not in ['draft', 'eight', 'stop']:
            returnDict = {'code': 400, 'message': '删除失败！只有草稿或退回流程可以删除。'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        MakeCopy.objects.filter(process_id=flow_id, type='i').delete()
        obj.objectauditrecord_set.all().delete()
        obj.audit_users_already.clear()
        obj.current_audit_users.clear()
        obj.delete()
        returnDict = {'code': 200, 'message': '删除成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ManagementEconomicContract(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')

        contract = request.GET.get("contract", "")

        obj = ContractManagement.objects.filter(Q(contract_name__contains=contract))
        context = {'realname': request.user.real_name, 'position': request.user.post, 'department': request.user.company.name, "obj": obj, "contract": contract}
        return render(request, 'finance/ManagementEconomicContract.html', context)

    def post(self, request):
        contract_name = request.POST.get('contract_name', None)                 # 合同名称
        start_time = request.POST.get('start_time', None)  # 合同开始时间
        end_time = request.POST.get('end_time', None)  # 合同截止日
        describe = request.POST.get('describe', None)  # 描述
        ReminderMethod = request.POST.get('ReminderMethod', None)  # 截止日通知方式
        pdf_path = request.POST.get('pdf_path', None)  # 合同文件路径

        EndTime = datetime.strptime(end_time, "%Y-%m-%d")
        remind_date = EndTime - relativedelta(months=3)

        if remind_date >= datetime.now():
            handle = "1"
        else:
            handle = "2"

        obj = ContractManagement.objects.create(contract_name=contract_name, contract_effect=start_time, contract_off=end_time, remind_date=remind_date, handle=handle, remind_type=ReminderMethod,
                                                contract_path=pdf_path, describe=describe, apply_user=request.user)

        returnData = {'code': 200, 'message': '上传成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 科研经费申请列表
class ResearchFundingList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "table_name": "finance_researchfunding"}
        return render(request, 'finance/research_funding_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.researchfunding_set.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.company.name,
                      'pay_reason': obj.pay_reason,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='research_funding_darf.html?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>" if obj.state == 'draft' else (
                          f"<a href='research_funding_detail.html?id={obj.id}'>查看</a> | <a href='research_funding_detail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state in [
                              'one', 'two', 'three'] else (f"<a href='research_funding_detail.html?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"if obj.state == 'stop' else f"<a href='research_funding_detail.html?id={obj.id}'>查看</a>")),
                      'state': obj.get_str_state(),
                      'total_money': obj.total_money}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ResearchFundingIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'uuid': uuid.uuid1()}
        return render(request, 'finance/research_funding_index.html', context)

    def post(self, request):
        # apply_user = request.user
        # company = request.user.company
        # Subject_id = request.POST.get('id', None)
        # pay_reason = request.POST.get("pay_reason", "")
        # rask = request.POST.get("rask", "")
        # total_money = request.POST.get("total_money", "")
        # daxie = request.POST.get("daxie", "")
        # back = request.POST.get("back", "")
        # people_type = request.POST.get("people_type", "")
        # pay_detail = request.POST.get("pay_detail", "")
        # fj_number = request.POST.get("fj_number", "")
        # admin_flag = request.POST.get("admin", "")
        # payee = request.POST.get("payee", "")
        # account_number = request.POST.get("account_number", "")
        # # ************************************************ 保存操作记录 ************************************
        # try:
        #     RecordAndPush().OperationRecords(request, "科研经费")
        # except:
        #     pass
        # try:
        #     float(total_money.replace(",", ""))
        # except Exception as E:
        #     returnDict = {'code': 400, 'message': '总金额需为数字！'}
        #     return HttpResponse(json.dumps(returnDict), content_type="application/json")
        #
        # if Subject_id:
        #     obj = ResearchFunding.objects.get(id=int(Subject_id))
        #     obj.pay_reason = pay_reason
        #     obj.total_money = total_money
        #     obj.fj_number = fj_number
        #     obj.pay_detail = pay_detail
        #     obj.people_type = people_type
        #     obj.daxie = daxie
        #     obj.rask = rask
        #     obj.payee = payee
        #     obj.account_number = account_number
        #     if back and not admin_flag:
        #         obj.researchfundingrecord_set.filter(state='unaudit').delete()
        #         obj.current_audit_users.clear()
        # else:
        #     obj = ResearchFunding.objects.create(apply_user=apply_user, company=company, pay_detail=pay_detail, total_money=total_money, payee=payee, account_number=account_number,
        #                                             pay_reason=pay_reason, fj_number=fj_number, daxie=daxie, rask=rask, people_type=people_type)
        # if not admin_flag:
        #     one_step = company.head_people
        #     flag = True
        #     if apply_user != one_step:
        #         ResearchFundingRecord.objects.create(node='one', audit_note='', audit_people=one_step, parent_id=obj)
        #         obj.state = 'one'
        #         obj.current_audit_users.add(one_step)
        #         flag = False
        #
        #     two_setp = Company.objects.get(id=14).head_people
        #     ResearchFundingRecord.objects.create(node='two', audit_note='', audit_people=two_setp, parent_id=obj)
        #     if flag:
        #         obj.state = 'two'
        #         obj.current_audit_users.add(two_setp)
        #
        #     three_setp = Company.objects.get(id=14).leaders_id
        #     ResearchFundingRecord.objects.create(node='three', audit_note='', audit_people=three_setp, parent_id=obj)
        #
        #     four_setp = Company.objects.get(id=23).head_people
        #     ResearchFundingRecord.objects.create(node='four', audit_note='', audit_people=four_setp, parent_id=obj)
        #
        #     five_setp = Staffing.objects.get(station='工会主席').post_personnel.all().first() if float(total_money.replace(",", "")) <= 10000 else Staffing.objects.get(station='院长').post_personnel.all().first() if 10000 < float(total_money.replace(",", "")) <= 200000 else Staffing.objects.get(station='书记').post_personnel.all().first()
        #     ResearchFundingRecord.objects.create(node='five', audit_note='', audit_people=five_setp, parent_id=obj)
        #
        #     six_setp = Staffing.objects.get(station='财务支付').post_personnel.all().first()
        #     ResearchFundingRecord.objects.create(node='six', audit_note='', audit_people=six_setp, parent_id=obj)
        #
        #     # ********************************************** 发送小程序推送 ******************************************
        #     topic_type = "科研经费"
        #     applicant = obj.apply_user.real_name
        #     ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        #     SubjectMatter = obj.pay_reason[:15] + "……" if len(obj.pay_reason) > 15 else obj.pay_reason
        #     for jj in obj.current_audit_users.all():
        #         try:
        #             RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
        #         except:
        #             pass
        # obj.save()
        # returnDict = {'status': 'success', 'message': "", 'code': 200}
        returnDict = {'status': 'success', 'message': "该流程已关闭，现已无法申请！", 'code': 400}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 科研经费申请详情&审批
class ResearchFundingDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ResearchFunding.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.researchfundingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.researchfundingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false',
                   'flow_dict': flow_dict, "revise": revise, "pay_detail": json.loads(obj.pay_detail),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace( "\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/research_funding_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "科研经费")
        except:
            pass
        obj = ResearchFunding.objects.get(id=int(id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.researchfundingrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.researchfundingrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.researchfundingrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.researchfundingrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.researchfundingrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.researchfundingrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.researchfundingrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.researchfundingrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.researchfundingrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.researchfundingrecord_set.filter(node='six', state='unaudit').first()
                obj_state = 'six'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.researchfundingrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                obj_state = 'seven'
                if obj.people_type == "1":
                    try:
                        headers = {
                            "Content-Type": 'application/json'
                        }
                        for rson in json.loads(obj.pay_detail):
                            post_data = {
                                'key': 'hOJYdf7WoMTZV06Q',
                                'department_name': obj.company.name,
                                'time': obj.create_time.strftime("%Y-%m-%d"),
                                'amount': float(rson['budget_amount'].replace(",", '')) / 10000,
                                'agent_name': obj.apply_user.real_name,
                                'reason': rson['goods_name']
                            }
                            req = requests.post(url=post_url, headers=headers, data=json.dumps(post_data))
                            print(req.text)
                    except:
                        print("同步更新出错")

            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "科研经费"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.pay_reason[:15] + "……" if len(obj.pay_reason) > 15 else obj.pay_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

# 科研经费草稿
class ResearchFundingDarf(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ResearchFunding.objects.get(id=id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.researchfundingrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state,
                                                  'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.researchfundingrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state,
                                              'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size,
                      "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                   "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'flow_dict': flow_dict, "revise": revise, "pay_detail": json.loads(obj.pay_detail),
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace( "\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/research_funding_darf.html', context)

    def post(self, request):
        apply_user = request.user
        company = request.user.company
        Subject_id = request.POST.get('id', None)
        pay_reason = request.POST.get("pay_reason", "")
        pay_type = request.POST.get("pay_type", "")
        rask = request.POST.get("rask", "")
        people_type = request.POST.get("people_type", "")
        total_money = request.POST.get("total_money", "")
        daxie = request.POST.get("daxie", "")
        pay_detail = request.POST.get("pay_detail", "")
        fj_number = request.POST.get("fj_number", "")
        revise = request.POST.get("revise", "")
        payee = request.POST.get("payee", "")
        account_number = request.POST.get("account_number", "")
        if Subject_id:
            obj = ResearchFunding.objects.get(id=int(Subject_id))
            obj.pay_reason = pay_reason
            obj.total_money = total_money
            obj.people_type = people_type
            obj.pay_type = pay_type
            obj.pay_detail = pay_detail
            obj.daxie = daxie
            obj.rask = rask
            obj.payee = payee
            obj.account_number = account_number
            if not revise:
                obj.state = "draft"
            obj.save()
        else:
            obj = ResearchFunding.objects.create(apply_user=apply_user, company=company, pay_type=pay_type, pay_detail=pay_detail, total_money=total_money, payee=payee, account_number=account_number,
                                                    pay_reason=pay_reason, fj_number=fj_number, daxie=daxie, rask=rask, state="draft", people_type=people_type)
        returnDict = {'status': 'success', 'message': "", 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

# 科研经费中止
class ResearchFundingStop(View):
    def post(self, request):
        sub_id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        obj = ResearchFunding.objects.get(id=int(sub_id))
        obj.state = state
        obj.current_audit_users.clear()
        obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class payment_process_list(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'finance/payment_process_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.paymentapproval_set.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'apply_user': obj.apply_user.real_name,
                      'company': obj.apply_user.company.name,
                      'title': obj.title,
                      'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='research_funding_darf.html?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>" if obj.state == 'draft' else (
                          f"<a href='payment_process_detail.html?id={obj.id}'>查看</a> | <a href='payment_process_detail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state in [
                              'one', 'two', 'three', 'four', 'five'] else (f"<a href='payment_process_detail.html?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"if obj.state == 'stop' else f"<a href='payment_process_detail.html?id={obj.id}'>查看</a>")),
                      'state': obj.get_state_str(),
                      'total_money': obj.total_money}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class payment_process_index(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        bgs_flag = 'true' if request.user.company.id == 80 else 'false'
        leaders_obj = User.objects.filter(group_id__in=[1, 2], is_delete=False)
        returndata = Company.objects.filter(~Q(id=87)).order_by("serial_number")
        company_list, ComList = [], []
        for c in returndata:
            if c.name not in ComList:
                one_dict = {"id": c.id, "name": c.name}
                company_list.append(one_dict)
                ComList.append(c.name)
        BeforehandObj = BeforehandReception.objects.filter(apply_user=request.user, relevance='0', state='end')
        ReceptionObj = ReceptionChecklist.objects.filter(apply_user=request.user, relevance='0', state='end')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'uuid': uuid.uuid1(), 'bgs_flag': bgs_flag,
                   'leaders_obj': leaders_obj, 'company_list': company_list, 'BeforehandObj': BeforehandObj, 'ReceptionObj': ReceptionObj}
        return render(request, 'finance/payment_process_index.html', context)

    def post(self, request):
        apply_user = request.user
        company = request.user.company
        id = request.POST.get('id', None)
        daxie = request.POST.get('daxie', None)  # 大写
        total_money = request.POST.get('total_money', 0)  # 总金额
        fj_number = request.POST.get('fj_number', None)
        rask = request.POST.get('rask', None)  # 备注
        payee = request.POST.get('payee', None)  # 收款单位
        payee_account = request.POST.get('payee_account', None)  # 收款账号
        source_funds = request.POST.get('source_funds', None)  # 经费来源
        pay_reason = request.POST.get('pay_reason', None)  # 付款事由
        BankDeposit = request.POST.get('BankDeposit', None)  # 开户行
        pay_type_select = request.POST.get('pay_type_select', None)             # 付款类型
        fenguan_leader = request.POST.get('fenguan_leader', '')
        PreReceptionId = request.POST.get('PreReceptionId', '')
        ReceptionChecklistId = request.POST.get('ReceptionChecklistId', '')
        expense_category = request.POST.get('expense_category', '')
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "付款流程")
        except:
            pass
        if id:
            obj = PaymentApproval.objects.get(id=id)
            obj.pay_type = pay_type_select
            obj.Payee = payee
            obj.receiving_account = payee_account
            obj.opening_bank = BankDeposit
            obj.title = pay_reason
            obj.source = source_funds
            obj.total_money = total_money
            obj.daxie = daxie
            obj.node = rask
            obj.fj_number = fj_number
            obj.expense_category = expense_category
            obj.save()
            obj.paymentapprovalrecord_set.filter(state='unaudit').delete()
            obj.current_audit_users.clear()
            message = '修改成功！'
        else:
            obj = PaymentApproval.objects.create(apply_user=apply_user, pay_type=pay_type_select, Payee=payee, receiving_account=payee_account, opening_bank=BankDeposit, expense_category=expense_category,
                                                 title=pay_reason, source=source_funds, total_money=total_money, daxie=daxie, fj_number=fj_number, node=rask, company=request.user.company)
            message = '创建成功！'

        print("========================", PreReceptionId, ReceptionChecklistId)
        if PreReceptionId != "undefined" and PreReceptionId:
            try:
                BefObj = BeforehandReception.objects.get(id=int(PreReceptionId))
                obj.beforehand_parent = BefObj
                BefObj.relevance = "1"
                BefObj.save()
            except:
                pass

        if ReceptionChecklistId != "undefined" and ReceptionChecklistId:
            try:
                RecObj = ReceptionChecklist.objects.get(id=int(ReceptionChecklistId))
                obj.reception_parent = RecObj
                RecObj.relevance = "1"
                RecObj.save()
            except:
                pass

        one_step = company.head_people
        flag = True
        if apply_user != one_step:
            PaymentApprovalRecord.objects.create(node='one', audit_note='', audit_people=one_step, official_documents_id=obj)
            obj.state = 'one'
            obj.current_audit_users.add(one_step)
            flag = False

        flag3 = True
        demand_office = request.POST.get('demand_office', '')
        print("=============+++++++++++", demand_office)
        if demand_office:
            demand_office_list = re.findall('\((.*?)\)', demand_office)
            for demand in demand_office_list:
                zero_step = Company.objects.get(id=int(demand)).head_people
                PaymentApprovalRecord.objects.create(node='zero', audit_note='', audit_people=zero_step, official_documents_id=obj)
                if flag:
                    obj.state = 'zero'
                    obj.current_audit_users.add(zero_step)
                    flag3 = False

        flag2 = True
        if obj.pay_type in ["5", "6"]:
            flag2 = False
            six_setp = Company.objects.get(id=14)
            PaymentApprovalRecord.objects.create(node='six', audit_note='', audit_people=six_setp.head_people, official_documents_id=obj)
            if flag and flag3:
                obj.state = 'six'
                obj.current_audit_users.add(six_setp.head_people)
            PaymentApprovalRecord.objects.create(node='two', audit_note='', audit_people=six_setp.leaders_id, official_documents_id=obj)

        flag1 = True
        if obj.pay_type not in ["5", "6"]:
            if company.id != 80:
                flag1 = False
                two_setp = company.leaders_id
                PaymentApprovalRecord.objects.create(node='two', audit_note='', audit_people=two_setp, official_documents_id=obj)
                if flag and flag2 and flag3:
                    obj.state = 'two'
                    obj.current_audit_users.add(two_setp)
            else:
                print("====================", fenguan_leader)
                if fenguan_leader != '0':
                    flag1 = False
                    two_setp = User.objects.get(id=int(fenguan_leader))
                    PaymentApprovalRecord.objects.create(node='two', audit_note='', audit_people=two_setp, official_documents_id=obj)
                    if flag and flag2 and flag3:
                        obj.state = 'two'
                        obj.current_audit_users.add(two_setp)

        PaymentApprovalRecord.objects.create(node='three', audit_note='', audit_people=Company.objects.get(id=23).head_people, official_documents_id=obj)
        if flag and flag2 and flag1 and flag3:
            obj.state = 'three'
            obj.current_audit_users.add(Company.objects.get(id=23).head_people)
        PaymentApprovalRecord.objects.create(node='four', audit_note='', audit_people=Staffing.objects.get(station='总会计师').post_personnel.all().first(), official_documents_id=obj)
        if obj.pay_type == '8':
            PaymentApprovalRecord.objects.create(node='five', audit_note='', audit_people=Staffing.objects.get(station="工会经费支付").post_personnel.all().first(), official_documents_id=obj)
        else:
            PaymentApprovalRecord.objects.create(node='five', audit_note='', audit_people=Staffing.objects.get(station="财务支付").post_personnel.all().first(), official_documents_id=obj)
        obj.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "付款流程"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': message}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class payment_process_detail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = PaymentApproval.objects.get(id=id)
        if obj.topics_id:
            audit_dic = {}
            topics_obj = obj.topics_id
            for audit_obj in topics_obj.topicsauditrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state, 'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
            main_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                 "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "pdf_path": atta_obj.pdf_path,
                 "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
                 "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0")]
            flow_file_list = [
                {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                 "pdf_path": atta_obj.pdf_path, "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name, "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                 "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)
            ]
            topic_audit_dic, topic_flow_dict = {}, {}
            for audit_obj in obj.paymentapprovalrecord_set.all():
                if audit_obj.node in topic_audit_dic:
                    topic_audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in obj.paymentapprovalrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    topic_flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in topic_flow_dict]) + 1}
                    topic_audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
            help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])

            received_audit_dic, company_type = {}, ''
            if topics_obj.received_foreign:
                received_obj = topics_obj.received_foreign
                company_type = "yb" if topics_obj.received_foreign.apply_user.company.id == 80 else "db"
                for audit_obj in received_obj.officialdocumentsauditrecord_set.all():
                    if audit_obj.node in received_audit_dic:
                        received_audit_dic[audit_obj.node].append(
                            {'audit_user': audit_obj.audit_people.real_name,
                             'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                             'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                             'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                             'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                    else:
                        received_audit_dic[audit_obj.node] = [
                            {'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                             'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                             'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                             'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            data_dic = {'realname': real_name, 'position': request.user.post, 'department': request.user.company.name, 'apply_user': topics_obj.employee.real_name, 'state': topics_obj.get_state_display(),
                        'main_file_list': main_file_list+flow_file_list, 'number': topics_obj.number, 'topics_name': topics_obj.topics_name, "flow_file_list": flow_file_list,
                        'topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_text).decode()).decode()),
                        'topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_basis).decode()).decode()),
                        'solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.solution).decode()).decode()) if topics_obj.solution != "空" else "",
                        'db_topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_text).decode()).decode()) if topics_obj.db_topics_text else "",
                        'db_topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_basis).decode()).decode()) if topics_obj.db_topics_basis else "",
                        'db_solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_solution).decode()).decode()) if topics_obj.db_solution else "",
                        'topics_estimate': topics_obj.topics_estimate, 'help_department': help_department, 'help_department1': help_department1,
                        'jfly': topics_obj.jfly if topics_obj.jfly else "", 'ysje': topics_obj.ysje if topics_obj.ysje else "", 'uuid': obj.fj_number,
                        'audit_list': audit_dic, "topic_audit_dic": topic_audit_dic, "topic_flow_dict": topic_flow_dict, "obj": topics_obj, "flow_obj": obj,
                        "is_refer": 'true' if obj.state == 'zero' else 'false', 'received_audit_dic': received_audit_dic, 'company_type': company_type,
                        'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                        'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six"] and request.user in obj.current_audit_users.all() else 'false',
                        'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'eight'] and request.user == obj.apply_user else 'false',
                        'file_path': Topicsattachments.objects.filter(topics_number=topics_obj.uuid).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=topics_obj.uuid) else ''}
            return render(request, 'finance/payment_process_detail_transfer.html', data_dic)
        else:
            audit_dic, flow_dict = {}, {}
            for audit_obj in obj.paymentapprovalrecord_set.all():
                if audit_obj.node in audit_dic:
                    audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                      'state_display': audit_obj.get_state_display(),
                                                      'state': audit_obj.state, 'node': audit_obj.node,
                                                      'node_display': audit_obj.get_node_display(),
                                                      'audit_note': audit_obj.audit_note,
                                                      'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                      'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
                else:
                    apply_people = []
                    apply = 'true'
                    for obj_s in obj.paymentapprovalrecord_set.filter(node=audit_obj.node):
                        apply_people.append(obj_s.audit_people.real_name)
                        if obj_s.state == "unaudit":
                            apply = 'false'
                    flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                    audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

            file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                          "file_path": atta_obj.pdf_path.replace("\\", "/"),
                          "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                          "file_size": atta_obj.file_size,
                          "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                          "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                          "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

            bgs_flag = 'true' if request.user.company.id == 80 else 'false'
            leaders_obj = User.objects.filter(group_id__in=[1, 2], is_delete=False)
            returndata = Company.objects.filter(~Q(id=87)).order_by("serial_number")
            company_list, ComList = [], []
            for c in returndata:
                if c.name not in ComList:
                    one_dict = {"id": c.id, "name": c.name}
                    company_list.append(one_dict)
                    ComList.append(c.name)
            context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name,
                       "obj": obj, 'audit_dic': audit_dic, "file_list": file_list, "leaders_obj": leaders_obj, "company_list": company_list,
                       'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false',
                       'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', "six", "zero"] and request.user in obj.current_audit_users.all() else 'false',
                       'is_stop': 'true' if obj.state != 'end' and request.user == obj.apply_user else 'false',
                       'flow_dict': flow_dict, "revise": revise, "bgs_flag": bgs_flag,
                       'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                       }
            return render(request, 'finance/payment_process_detail.html', context)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "付款流程")
        except:
            pass
        obj = PaymentApproval.objects.get(id=int(id))

        if not obj.paymentapprovalrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnDict = {'code': 500, 'message': '流程已审核，请勿重复点击！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.paymentapprovalrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                if obj.paymentapprovalrecord_set.filter(node='zero', state='unaudit'):
                    next_audit_record = obj.paymentapprovalrecord_set.filter(node='zero', state='unaudit').first()
                    obj_state = 'zero'
                else:
                    if obj.paymentapprovalrecord_set.filter(node='six', state='unaudit'):
                        next_audit_record = obj.paymentapprovalrecord_set.filter(node='six', state='unaudit').first()
                        obj_state = 'six'
                    else:
                        if obj.paymentapprovalrecord_set.filter(node='two', state='unaudit'):
                            next_audit_record = obj.paymentapprovalrecord_set.filter(node='two', state='unaudit').first()
                            obj_state = 'two'
                        else:
                            next_audit_record = obj.paymentapprovalrecord_set.filter(node='three', state='unaudit').first()
                            obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'zero':
            audit_record = obj.paymentapprovalrecord_set.filter(node='zero', state='unaudit').first()
            if state == 'audit':
                if obj.paymentapprovalrecord_set.filter(node='six', state='unaudit').count():
                    next_audit_record = obj.paymentapprovalrecord_set.filter(node='six', state='unaudit').first()
                    obj_state = 'six'
                elif obj.paymentapprovalrecord_set.filter(node='two', state='unaudit').count():
                    next_audit_record = obj.paymentapprovalrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                else:
                    next_audit_record = obj.paymentapprovalrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.paymentapprovalrecord_set.filter(node='six', state='unaudit').first()
            if state == 'audit':
                if obj.paymentapprovalrecord_set.filter(node='two', state='unaudit'):
                    next_audit_record = obj.paymentapprovalrecord_set.filter(node='two', state='unaudit').first()
                    obj_state = 'two'
                else:
                    next_audit_record = obj.paymentapprovalrecord_set.filter(node='three', state='unaudit').first()
                    obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.paymentapprovalrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.paymentapprovalrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.paymentapprovalrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.paymentapprovalrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.paymentapprovalrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.paymentapprovalrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.paymentapprovalrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                obj_state = 'end'
                try:
                    if obj.topics_id.received_foreign:
                        obj.topics_id.received_foreign.current_audit_users.clear()
                        obj.topics_id.received_foreign.audit_users_already.add(obj.apply_user)
                        obj.topics_id.received_foreign.state = 'six'
                        obj.topics_id.received_foreign.type = "e"
                        obj.topics_id.received_foreign.save()
                except:
                    pass
                if obj.pay_type in ["5", "6"]:
                    try:
                        headers = {
                            "Content-Type": 'application/json'
                        }
                        post_data = {
                            'key': 'hOJYdf7WoMTZV06Q',
                            'department_name': obj.apply_user.company.name,
                            'time': obj.create_time.strftime("%Y-%m-%d"),
                            'amount': re.findall("\d+.\d+", obj.topics_id.ysje)[0] if obj.topics_id else float(obj.total_money.replace(",", '')) / 10000,
                            'agent_name': obj.apply_user.real_name, 'reason_detail': obj.title,
                            'reason': obj.get_expense_type()
                        }
                        req = requests.post(url=post_url, headers=headers, data=json.dumps(post_data))
                        print(req.text)
                    except:
                        print("同步更新出错")
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "付款流程"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")


class payment_process_stop(View):
    def post(self, request):
        id = request.POST.get('id', None)
        types = request.POST.get('types', 'stop')  # stop 终止 delete 删除
        obj = PaymentApproval.objects.get(id=int(id))
        if types == 'stop':
            if obj.state == 'end':
                returnData = {'code': 500, 'message': '终止失败，审批完毕的流程不能终止！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
            else:
                obj.current_audit_users.clear()
                obj.state = 'stop'
                obj.save()
                returnData = {'code': 200, 'message': '终止成功！'}
                return HttpResponse(json.dumps(returnData), content_type="application/json")
        else:
            print("===================")
            obj.current_audit_users.clear()
            obj.paymentapprovalrecord_set.all().delete()
            obj.audit_users_already.clear()
            obj.delete()
            returnData = {'code': 200, 'message': '删除成功！'}
            return HttpResponse(json.dumps(returnData), content_type="application/json")


class ContractDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ContractApproval.objects.get(id=id)
        audit_dic = {}
        topics_obj = obj.topics_id
        for audit_obj in topics_obj.topicsauditrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name,
                                              'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node,
                                              'node_display': audit_obj.get_node_display(),
                                              'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]
        main_file_list = [
            {"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
             "file_path": atta_obj.pdf_path.replace("\\", "/"),
             "pdf_path": atta_obj.pdf_path, "file_type": "0",
             "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
             "file_size": atta_obj.file_size, "uploader": atta_obj.uploader_user.real_name,
             "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
             "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=topics_obj.uuid, file_type="0")]

        file_flag, protocol_flag = "false", "false"

        for iiii in Topicsattachments.objects.filter(topics_number=obj.fj_number):
            if iiii.file_type == '1':
                file_flag = "true"
            if iiii.file_type == '3':
                protocol_flag = "true"
            main_file_list.append(
                {"file_name": iiii.file_name if iiii.file_name else iiii.file_path.name.split('/')[-1],
                 "file_path": iiii.pdf_path.replace("\\", "/"),
                 "pdf_path": iiii.pdf_path, "file_type": iiii.file_type,
                 "word_path": iiii.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                 "file_size": iiii.file_size, "uploader": iiii.uploader_user.real_name,
                 "upload_time": str(iiii.create_time).split(".")[0][:-3],
                 "id": iiii.id}
            )

        topic_audit_dic, topic_flow_dict = {}, {}
        for audit_obj in obj.contractapprovalrecord_set.all():
            if audit_obj.node in topic_audit_dic:
                topic_audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name,
                                                  'state_display': audit_obj.get_state_display(), 'state': audit_obj.state, 'node': audit_obj.node,
                                                  'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                                  'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.contractapprovalrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                topic_flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in topic_flow_dict]) + 1}
                topic_audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                              'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        help_department = ' ,'.join([i.name for i in topics_obj.help_department.all()])
        help_department1 = ' ,'.join([f"{i.name}({i.id})" for i in topics_obj.help_department.all()])
        if Topicsattachments.objects.filter(topics_number=topics_obj.uuid):
            file_path = Topicsattachments.objects.filter(topics_number=topics_obj.uuid).first().pdf_path.replace("\\", "/")
        elif Topicsattachments.objects.filter(topics_number=obj.fj_number):
            file_path = Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/")
        else:
            file_path = ""
        print("===============", topics_obj.get_funding_source())
        data_dic = {'realname': real_name, 'position': request.user.post, 'department': request.user.company.name, 'apply_user': topics_obj.employee.real_name, 'state': topics_obj.get_state_display(),
                    'main_file_list': main_file_list, 'number': topics_obj.number, 'topics_name': topics_obj.topics_name, 'protocol_flag': protocol_flag, 'FundingSource': topics_obj.get_funding_source(),
                    'topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_text).decode()).decode()),
                    'topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.topics_basis).decode()).decode()),
                    'solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.solution).decode()).decode()) if topics_obj.solution != "空" else "",
                    'db_topics_text': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_text).decode()).decode()) if topics_obj.db_topics_text else "",
                    'db_topics_basis': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_topics_basis).decode()).decode()) if topics_obj.db_topics_basis else "",
                    'db_solution': urllib.parse.unquote(base64.b64decode(base64.b64decode(topics_obj.db_solution).decode()).decode()) if topics_obj.db_solution else "",
                    'topics_estimate': topics_obj.topics_estimate, 'help_department': help_department, 'help_department1': help_department1, "file_flag": file_flag,
                    'jfly': topics_obj.jfly if topics_obj.jfly else "", 'ysje': topics_obj.ysje if topics_obj.ysje else "", "uuid": uuid.uuid4(),
                    'audit_list': audit_dic, "topic_audit_dic": topic_audit_dic, "topic_flow_dict": topic_flow_dict, "obj": topics_obj, "flow_obj": obj,
                    'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false', "file_uuid": uuid.uuid4(),
                    'is_audit': 'true' if obj.state in ['negative', 'zero', 'one', 'two', 'three', 'four', 'five', "six", "seven"] and request.user in obj.current_audit_users.all() else 'false',
                    'is_stop': 'true' if obj.state in ['negative', 'zero', 'one', 'two', 'three', 'four', 'five', 'six', "seven"] and request.user == obj.apply_user else 'false',
                    'file_path': file_path}
        return render(request, 'finance/ContractDetail.html', data_dic)

    def post(self, request):
        id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "付款流程")
        except:
            pass

        obj = ContractApproval.objects.get(id=int(id))
        if not obj.contractapprovalrecord_set.filter(node=obj.state, state='unaudit', audit_people=request.user).count():
            returnDict = {'code': 500, 'message': '流程已审批，请勿重复点击！'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'negative':
            negative_uuid = request.POST.get('negative_uuid', '')
            contract_type_select = request.POST.get('contract_type_select', '')
            opposite_unit = request.POST.get('opposite_unit', '')
            contract_name = request.POST.get('contract_name', '')
            contract_number = request.POST.get('contract_number', '')
            audit_record = obj.contractapprovalrecord_set.filter(node='negative', state='unaudit').first()
            next_audit_record = obj.contractapprovalrecord_set.filter(node='zero', state='unaudit').first()
            obj_state = 'zero'
            state = "audit"
            obj.current_audit_users.add(next_audit_record.audit_people)
            obj.fj_number = negative_uuid
            obj.topics_id.contract_type = contract_type_select
            obj.topics_id.contract_name = contract_name
            obj.topics_id.contract_number = contract_number
            obj.topics_id.Payee = opposite_unit
            obj.topics_id.save()

        elif obj.state == 'zero':
            audit_record = obj.contractapprovalrecord_set.filter(node='zero', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.contractapprovalrecord_set.filter(node='one', state='unaudit').first()
                obj_state = 'one'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'one':
            audit_record = obj.contractapprovalrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.contractapprovalrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.contractapprovalrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.contractapprovalrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.contractapprovalrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.contractapprovalrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.contractapprovalrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.contractapprovalrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.contractapprovalrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                # obj_state = 'end'
                obj_state = 'seven'
                try:
                    obj.current_audit_users.add(obj.topics_id.help_department.all().first().head_people)
                except:
                    obj.current_audit_users.add(obj.apply_user)
                MakeCopy.objects.create(recipient=Company.objects.get(id=9).head_people, process_id=obj.id, type='p')
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'six':
            audit_record = obj.contractapprovalrecord_set.filter(node='six', state='unaudit').first()
            if state == 'submit':
                negative_uuid = request.POST.get('negative_uuid', '')
                obj.fj_number = negative_uuid
                next_audit_record = obj.contractapprovalrecord_set.filter(node='zero', state='unaudit').first()
                obj_state = 'zero'
                state = 'audit'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "付款流程"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.title[:15] + "……" if len(obj.title) > 15 else obj.title
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class DataExportList(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name}
        return render(request, 'finance/data_export_list.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        user = request.user
        objs = user.confidentialdataexport_set.all().order_by('-create_time')
        data_list = [{'id': obj.id,
                      'application_reason': obj.application_reason, 'data_type': obj.get_type_str(), 'date': obj.create_time.strftime("%Y-%m-%d"),
                      'current_audit_users': ', '.join([u.real_name for u in obj.current_audit_users.all()]),
                      "url": f"<a href='data_export_draft.html?id={obj.id}'>编辑</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>" if obj.state == 'draft' else (
                          f"<a href='data_export_detail.html?id={obj.id}'>查看</a> | <a href='data_export_detail.html?revise=true&id={obj.id}'>修改</a>" if obj.can_revise == '1' and obj.state in [
                              'one', 'two', 'three', 'four', 'five', 'six'] else (f"<a href='payment_process_detail.html?id={obj.id}'>查看</a> | <a href='' id={obj.id} onclick='del_draft(this.id)' style='color:red;'>删除</a>"if obj.state == 'stop' else f"<a href='data_export_detail.html?id={obj.id}'>查看</a>")),
                      'state': obj.get_state_str()}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class DataExportIndex(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        company_list = [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]
        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, 'company_list': company_list, 'uuid': uuid.uuid4()}
        return render(request, 'finance/data_export_index.html', context)

    def post(self, request):
        flow_id = request.POST.get("flow_id", "")
        application_reason = request.POST.get("application_reason", "")
        external_guidance_basis = request.POST.get("external_guidance_basis", "")
        data_type = request.POST.get("data_type", "")
        inspection_report = request.POST.get("inspection_report", "")
        meet_or_not = request.POST.get("meet_or_not", "")
        fj_number = request.POST.get("fj_number", "")

        if flow_id:
            obj = ConfidentialDataExport.objects.get(id=int(flow_id))
            obj.application_reason = application_reason
            obj.external_guidance_basis = external_guidance_basis
            obj.information_type = data_type
            obj.inspection_report = inspection_report
            obj.meet_or_not = meet_or_not
            obj.current_audit_users.clear()
            obj.confidentialdataexportrecord_set.filter(state='unaudit').delete()
        else:
            obj = ConfidentialDataExport.objects.create(apply_user=request.user, company=request.user.company, information_type=data_type, meet_or_not=meet_or_not,
                                                        external_guidance_basis=external_guidance_basis, inspection_report=inspection_report, fj_number=fj_number, application_reason=application_reason)
        flag = True
        if request.user != request.user.company.head_people:
            ConfidentialDataExportRecord.objects.create(parent_id=obj, state='unaudit', node='one', audit_people=request.user.company.head_people, audit_note='')
            obj.current_audit_users.add(request.user.company.head_people)
            obj.state = 'one'
            flag = False

        if obj.information_type == 'one':
            two_step = Company.objects.get(id=13)
        elif obj.information_type == 'two':
            two_step = Company.objects.get(id=23)
        elif obj.information_type == 'three':
            two_step = Company.objects.get(id=26)
        elif obj.information_type == 'four':
            two_step = Company.objects.get(id=16)
        elif obj.information_type == 'five':
            two_step = Company.objects.get(id=75)
        elif obj.information_type == 'seven':
            two_step = Company.objects.get(id=32)
        elif obj.information_type == 'eight':
            two_step = Company.objects.get(id=22)
        else:
            two_step = Company.objects.get(id=31)

        ConfidentialDataExportRecord.objects.create(parent_id=obj, state='unaudit', node='two', audit_people=two_step.head_people, audit_note='')
        if flag:
            obj.current_audit_users.add(two_step.head_people)
            obj.state = 'two'
        ConfidentialDataExportRecord.objects.create(parent_id=obj, state='unaudit', node='three', audit_people=two_step.leaders_id, audit_note='')
        ConfidentialDataExportRecord.objects.create(parent_id=obj, state='unaudit', node='four', audit_people=Company.objects.get(id=31).head_people, audit_note='')
        ConfidentialDataExportRecord.objects.create(parent_id=obj, state='unaudit', node='five', audit_people=Company.objects.get(id=31).leaders_id, audit_note='')
        # if obj.inspection_report == '1':
        #     ConfidentialDataExportRecord.objects.create(parent_id=obj, state='unaudit', node='seven', audit_people=, audit_note='')
        obj.save()
        returnDict = {'status': 'success', 'message': "", 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class DataExportDraft(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ConfidentialDataExport.objects.get(id=id)
        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1],
                      "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, "file_list": file_list, "revise": revise,
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/data_export_draft.html', context)

    def post(self, request):
        flow_id = request.POST.get("flow_id", "")
        application_reason = request.POST.get("application_reason", "")
        external_guidance_basis = request.POST.get("external_guidance_basis", "")
        data_type = request.POST.get("data_type", "")
        inspection_report = request.POST.get("inspection_report", "")
        meet_or_not = request.POST.get("meet_or_not", "")
        fj_number = request.POST.get("fj_number", "")

        if flow_id:
            obj = ConfidentialDataExport.objects.get(id=int(flow_id))
            obj.application_reason = application_reason
            obj.external_guidance_basis = external_guidance_basis
            obj.information_type = data_type
            obj.inspection_report = inspection_report
            obj.meet_or_not = meet_or_not
        else:
            obj = ConfidentialDataExport.objects.create(apply_user=request.user, company=request.user.company, information_type=data_type, meet_or_not=meet_or_not,
                                                        external_guidance_basis=external_guidance_basis, inspection_report=inspection_report, fj_number=fj_number, application_reason=application_reason)
        obj.state = 'draft'
        obj.save()
        returnDict = {'status': 'success', 'message': "", 'code': 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class DataExportDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except:
            return redirect('/')
        flow_id = request.GET.get('id', None)
        revise = request.GET.get('revise', '')
        obj = ConfidentialDataExport.objects.get(id=flow_id)
        audit_dic, flow_dict = {}, {}
        for audit_obj in obj.confidentialdataexportrecord_set.all():
            if audit_obj.node in audit_dic:
                audit_dic[audit_obj.node].append({'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(),
                                                  'state': audit_obj.state, 'node': audit_obj.node, 'node_display': audit_obj.get_node_display(),
                                                  'audit_note': audit_obj.audit_note, 'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                                  'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''})
            else:
                apply_people = []
                apply = 'true'
                for obj_s in obj.confidentialdataexportrecord_set.filter(node=audit_obj.node):
                    apply_people.append(obj_s.audit_people.real_name)
                    if obj_s.state == "unaudit":
                        apply = 'false'
                flow_dict[audit_obj.node] = {'apply': apply, 'apply_people': ','.join(list(set(apply_people))), 'sear': len([i for i in flow_dict]) + 1}
                audit_dic[audit_obj.node] = [{'audit_user': audit_obj.audit_people.real_name, 'state_display': audit_obj.get_state_display(), 'state': audit_obj.state,
                                              'node': audit_obj.node, 'node_display': audit_obj.get_node_display(), 'audit_note': audit_obj.audit_note,
                                              'audit_time': audit_obj.update_time.strftime("%Y-%m-%d %H:%M") if audit_obj.state != 'unaudit' else '',
                                              'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}]

        file_list = [{"file_name": atta_obj.file_name if atta_obj.file_name else atta_obj.file_path.name.split('/')[-1], "file_path": atta_obj.pdf_path.replace("\\", "/"),
                      "word_path": atta_obj.file_path.path.replace("\\", "/").replace(os.getcwd().replace("\\", "/") + "/media/", ""),
                      "file_size": atta_obj.file_size, "uploader": User.objects.get(username=atta_obj.uploader).real_name,
                      "upload_time": str(atta_obj.create_time).split(".")[0][:-3],
                      "id": atta_obj.id} for atta_obj in Topicsattachments.objects.filter(topics_number=obj.fj_number)]

        context = {'realname': real_name, 'position': request.user.post, "department": request.user.company.name, "obj": obj, 'audit_dic': audit_dic, "file_list": file_list,
                   'is_edit': 'true' if (obj.state == 'eight' and obj.apply_user == request.user) or revise else 'false', 'flow_dict': flow_dict, "revise": revise,
                   'is_audit': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] and request.user in obj.current_audit_users.all() else 'false',
                   'is_stop': 'true' if obj.state in ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'] and request.user == obj.apply_user else 'false',
                   'file_path': Topicsattachments.objects.filter(topics_number=obj.fj_number).first().pdf_path.replace("\\", "/") if Topicsattachments.objects.filter(topics_number=obj.fj_number) else ""
                   }
        return render(request, 'finance/data_export_detail.html', context)

    def post(self, request):
        flow_id = request.POST.get('id', None)
        audit_note = request.POST.get('audit_note', '同意')
        state = request.POST.get("state", None)  # draft 拒绝 audit 通过
        # ************************************************ 保存操作记录 ************************************
        try:
            RecordAndPush().OperationRecords(request, "数据外导")
        except:
            pass
        obj = ConfidentialDataExport.objects.get(id=int(flow_id))
        obj.audit_users_already.add(request.user)
        obj.current_audit_users.clear()
        if obj.state == 'one':
            audit_record = obj.confidentialdataexportrecord_set.filter(node='one', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.confidentialdataexportrecord_set.filter(node='two', state='unaudit').first()
                obj_state = 'two'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'two':
            audit_record = obj.confidentialdataexportrecord_set.filter(node='two', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.confidentialdataexportrecord_set.filter(node='three', state='unaudit').first()
                obj_state = 'three'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'three':
            audit_record = obj.confidentialdataexportrecord_set.filter(node='three', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.confidentialdataexportrecord_set.filter(node='four', state='unaudit').first()
                obj_state = 'four'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'four':
            audit_record = obj.confidentialdataexportrecord_set.filter(node='four', state='unaudit').first()
            if state == 'audit':
                next_audit_record = obj.confidentialdataexportrecord_set.filter(node='five', state='unaudit').first()
                obj_state = 'five'
                obj.current_audit_users.add(next_audit_record.audit_people)
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        elif obj.state == 'five':
            audit_record = obj.confidentialdataexportrecord_set.filter(node='five', state='unaudit').first()
            if state == 'audit':
                obj_state = 'end'
                MakeCopy.objects.create(recipient=Company.objects.get(id=18).head_people, process_id=obj.id, type='o')
                MakeCopy.objects.create(recipient=Staffing.objects.get(station="纪委书记").post_personnel.all().first(), process_id=obj.id, type='o')
                MakeCopy.objects.create(recipient=Staffing.objects.get(station="院长").post_personnel.all().first(), process_id=obj.id, type='o')
                MakeCopy.objects.create(recipient=Staffing.objects.get(station="书记").post_personnel.all().first(), process_id=obj.id, type='o')
            else:
                obj_state = 'eight'
                obj.current_audit_users.add(obj.apply_user)

        else:
            returnDict = {'code': 500, 'message': '状态不正确，不能审核'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.state = obj_state
        obj.can_revise = '0'
        obj.save()
        audit_record.update_time = datetime.now()
        audit_record.state = state
        audit_record.audit_note = audit_note
        audit_record.save()
        # ********************************************** 发送小程序推送 ******************************************
        topic_type = "数据外导"
        applicant = obj.apply_user.real_name
        ApplicationTime = obj.create_time.strftime("%Y-%m-%d %H:%M")
        SubjectMatter = obj.application_reason[:15] + "……" if len(obj.application_reason) > 15 else obj.application_reason
        for jj in obj.current_audit_users.all():
            try:
                RecordAndPush().MessagePush(jj.openid, topic_type, applicant, ApplicationTime, SubjectMatter)
            except:
                pass
        returnData = {'code': 200, 'message': '审核成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")

class DataExportStop(View):
    def post(self, request):
        delete_type = request.POST.get("type", None)
        sub_id = request.POST.get("id", None)
        state = request.POST.get("state", None)
        obj = ConfidentialDataExport.objects.get(id=int(sub_id))
        if delete_type:
            ConfidentialDataExportRecord.objects.filter(parent_id=obj).delete()
            obj.audit_users_already.clear()
            obj.current_audit_users.clear()
            obj.delete()
        else:
            obj.state = state
            obj.current_audit_users.clear()
            obj.save()
        returnData = {'code': 200, 'message': '操作成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")